예제 #1
0
class Main:
    def __init__(self):
        pygame.init()
        pygame.display.init()
        pygame.font.init()

        self.screen_w = pygame.display.Info().current_w
        self.screen_h = pygame.display.Info().current_h
        self.w = int(self.screen_h * 1.2)
        self.h = int(self.screen_h * 0.8)

        self.preferences = Preferences()
        self.fullscreen = self.preferences.get("fullscreen")
        self.go_mode()

        pygame.mouse.set_visible(False)

        pygame.display.set_caption(Constants.CAPTION)

    def go_mode(self):
        if self.fullscreen:
            self.mode = (self.screen_w, self.screen_h)
            if not self.mode in pygame.display.list_modes():
                self.mode = pygame.display.list_modes()[0]
            self.screen = pygame.display.set_mode(self.mode, pygame.FULLSCREEN)
        else:
            self.mode = (self.w, self.h)
            self.screen = pygame.display.set_mode(self.mode)
        self.unit = int(self.mode[1] / Constants.UNITS)

    def main(self):
        self.boot_screen()
        while True:
            if not self.title_screen():
                break
            if self.preferences.edit_flag:
                self.preferences.save()
                fullscreen = self.preferences.get("fullscreen")
                if self.fullscreen != fullscreen:
                    self.fullscreen = fullscreen
                    self.go_mode()
            else:
                self.play_game()

    def boot_screen(self):
        bs = BootScreen(self.screen, self.unit)
        bs.main()
        return bs.running

    def title_screen(self):
        self.go_mode()
        ts = TitleScreen(self.screen, self.unit, self.preferences)
        ts.main()
        return ts.running

    def play_game(self):
        gm = Game(self.screen, self.unit, self.preferences)
        gm.main()
        return gm.running
예제 #2
0
	def create(self, text):
		"""
		Takes a string of text, converts it using the PicoTTS engine, and plays it.
		Wave files are buffered in /tmp/OnoTTS/<text>.wav.
		First call blocks while PicoTTS generates the .wav, this may take about a second.
		Subsequent calls of the same text return immediately.
		If you wish to avoid this, sound files can be generated on beforehand by
		using generate_only=True.
		"""
		def format_filename(s):
			"""
			Take a string and return a valid filename constructed from the string.
			Uses a whitelist approach: any characters not present in valid_chars are
			removed. Also spaces are replaced with underscores.

			Note: this method may produce invalid filenames such as ``, `.` or `..`
			When I use this method I prepend a date string like '2009_01_15_19_46_32_'
			and append a file extension like '.txt', so I avoid the potential of using
			an invalid filename.

			Taken from: https://gist.github.com/seanh/93666
			"""
			valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
			filename = ''.join(c for c in s if c in valid_chars)
			filename = filename.replace(' ','_') # I don't like spaces in filenames.
			return filename

		if not os.path.exists("/tmp/OpsoroTTS/"):
			os.makedirs("/tmp/OpsoroTTS/")

		filename = format_filename(text)

		# Max length of filename is 255 chars
		if len(filename) >= 250:
			filename = filename[:250]
		full_path = os.path.join(get_path("/tmp/OpsoroTTS/"), filename + ".wav")

		# # Sound buffering
		# if os.path.isfile(full_path):
		# 	# Sound file already exists
		# 	return full_path

		self.engine = Preferences.get("audio", "tts_engine", self.engine)
		self.language = Preferences.get("audio", "tts_language", self.language)
		self.gender = Preferences.get("audio", "tts_gender", self.gender)

		if self.engine == "pico":
			self.create_pico(text, full_path)
		elif self.engine == "espeak":
			self.create_espeak(text, full_path, self.language, self.gender, self.delay, self.speed)

		return full_path
예제 #3
0
class Game:
    def __init__(self):
        pygame.init()

        #get preferences
        self.preferences = Preferences()

        #resolution, flags, depth, display
        self.unit = Constants.RESOLUTION[0] / Constants.UNITS
        self.banner = Banner()
        self.score_width = self.unit * 15

        if self.preferences.fullscreen:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),pygame.FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),0,32)

        pygame.display.set_caption(Constants.CAPTION)

        #game area surface
        self.gamescreen = pygame.Surface(Constants.RESOLUTION)
        #score area rectangle surface
        self.scorescreen = pygame.Surface(
            (self.score_width, Constants.RESOLUTION[1]))

        #Snake and foods manager
        self.me=Snake(color=pygame.color.THECOLORS[self.preferences.get("color")],\
                     nickname=self.preferences.get("nickname"))

        self.nickname = self.preferences.get("nickname")
        self.f = Foods()

        #Score manager
        self.scores = Scores((self.score_width, Constants.RESOLUTION[1]))

        #add our own score, the server will send us the remaining one at connection
        self.scores.new_score(self.preferences.get("nickname"),\
                        pygame.color.THECOLORS[self.preferences.get("color")])

        #game area background color
        self.gamescreen.fill(Constants.COLOR_BG)
        self.scorescreen.fill((100, 100, 100))

        #timers
        self.clock = pygame.time.Clock()
        self.current_time = 0

        self.move_snake_timer = Timer(1.0 / Constants.SNAKE_SPEED * 1000,
                                      self.current_time,
                                      periodic=True)
        self.blink_snake_timer = Timer(1.0 / Constants.SNAKE_BLINKING_SPEED *
                                       1000,
                                       self.current_time,
                                       periodic=True)
        self.blink_banner_timer = Timer(500, self.current_time, periodic=True)
        self.new_apple_timer = Timer(Constants.NEW_APPLE_PERIOD * 1000,
                                     self.current_time,
                                     periodic=True)

    def process_events(self):
        #key handling
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                if event.key == pygame.K_UP:
                    self.me.action(1)
                if event.key == pygame.K_DOWN:
                    self.me.action(2)
                if event.key == pygame.K_LEFT:
                    self.me.action(3)
                if event.key == pygame.K_RIGHT:
                    self.me.action(4)
                if event.key == pygame.K_SPACE:
                    self.me.set_ready()

    def run(self):
        whole_second = 0
        self.running = True
        while self.running:
            #time tracking
            self.current_time += self.clock.tick(Constants.FPS)

            #check if the snake is still alive
            if not self.me.alive:
                self.me.alive = True
                self.me.restart()

            #check if game need more food
            if self.new_apple_timer.expired(self.current_time):
                self.f.make()

            #check if we need to move our own snake's state
            #if we do, send an update of our position to
            #the server
            if self.move_snake_timer.expired(self.current_time):
                self.me.move()

            #check if we need to blink the unready snakes (unready state)
            if self.blink_snake_timer.expired(self.current_time):
                self.me.blink()

            #check if snake has eaten
            if self.me.ready:
                if self.f.check(self.me.head):
                    self.me.grow(Constants.GROW)
                    self.scores.inc_score(self.nickname, 1)

            #cleanup background
            self.gamescreen.fill(Constants.COLOR_BG)

            #draw scores
            self.scores.draw(self.screen)

            #draw all snakes positions as last seen by the server
            #we do not compute their positions ourselves!
            self.me.draw(self.gamescreen)

            #draw food
            self.f.draw(self.gamescreen)

            #process external events (keyboard,...)
            self.process_events()

            #then update display
            #update game area on screen container
            self.screen.blit(self.gamescreen, (self.score_width, 0))

            pygame.display.update()
예제 #4
0
class IssueView(BottomView, IPreferencesMonitor):
    """
	"""

    _log = getLogger("IssueView")

    label = "Issues"
    icon = gtk.STOCK_DIALOG_INFO
    scope = View.SCOPE_EDITOR

    def __init__(self, context, editor):
        BottomView.__init__(self, context)
        self._editor = editor
        self._handlers = {}

    def init(self, context):
        self._log.debug("init")

        self._preferences = Preferences()
        self._show_tasks = self._preferences.get_bool("IssuesShowTasks", True)
        self._show_warnings = self._preferences.get_bool(
            "IssuesShowWarnings", True)

        self._context = context

        self._icons = {
            Issue.SEVERITY_WARNING:
            pixbuf_new_from_file(find_resource("icons/warning.png")),
            Issue.SEVERITY_ERROR:
            pixbuf_new_from_file(find_resource("icons/error.png")),
            Issue.SEVERITY_INFO:
            None,
            Issue.SEVERITY_TASK:
            pixbuf_new_from_file(find_resource("icons/task.png"))
        }

        self._store = gtk.ListStore(Pixbuf, str, str, object)

        self._view = gtk.TreeView(self._store)

        column = gtk.TreeViewColumn()
        column.set_title("Message")

        pixbuf_renderer = gtk.CellRendererPixbuf()
        column.pack_start(pixbuf_renderer, False)
        column.add_attribute(pixbuf_renderer, "pixbuf", 0)

        text_renderer = gtk.CellRendererText()
        column.pack_start(text_renderer, True)
        column.add_attribute(text_renderer, "markup", 1)

        self._view.append_column(column)
        self._view.insert_column_with_attributes(-1,
                                                 "File",
                                                 gtk.CellRendererText(),
                                                 markup=2)
        self._handlers[self._view] = self._view.connect(
            "row-activated", self._on_row_activated)

        self._scr = gtk.ScrolledWindow()

        self._scr.add(self._view)
        self._scr.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._scr.set_shadow_type(gtk.SHADOW_IN)

        self.pack_start(self._scr, True)

        # toolbar

        self._button_warnings = gtk.ToggleToolButton()
        self._button_warnings.set_tooltip_text("Show/Hide Warnings")
        image = gtk.Image()
        image.set_from_file(find_resource("icons/warning.png"))
        self._button_warnings.set_icon_widget(image)
        self._button_warnings.set_active(self._show_warnings)
        self._handlers[self._button_warnings] = self._button_warnings.connect(
            "toggled", self.__on_warnings_toggled)

        self._button_tasks = gtk.ToggleToolButton()
        self._button_tasks.set_tooltip_text("Show/Hide Tasks")
        imageTask = gtk.Image()
        imageTask.set_from_file(find_resource("icons/task.png"))
        self._button_tasks.set_icon_widget(imageTask)
        self._button_tasks.set_active(self._show_tasks)
        self._handlers[self._button_tasks] = self._button_tasks.connect(
            "toggled", self.__on_tasks_toggled)

        toolbar = gtk.Toolbar()
        toolbar.set_orientation(gtk.ORIENTATION_VERTICAL)
        toolbar.set_style(gtk.TOOLBAR_ICONS)
        toolbar.set_icon_size(gtk.ICON_SIZE_MENU)
        toolbar.insert(self._button_warnings, -1)
        toolbar.insert(self._button_tasks, -1)

        self.pack_start(toolbar, False)

        self._issues = []
        self._preferences.register_monitor(self)

        self._log.debug("init finished")

    def _on_row_activated(self, view, path, column):
        """
		A row has been double-clicked on
		"""
        issue = self._store.get(self._store.get_iter(path), 3)[0]

        self._context.activate_editor(issue.file)

        #~ # FIXME: this doesn't work correctly
        #~ if not self._context.active_editor is None:
        #~ self._context.active_editor.select(issue.start, issue.end)
        self._editor.select(issue.start, issue.end)

    def _on_value_changed(self, key, value):
        if key == "IssuesShowWarnings" or key == "IssuesShowTasks":
            # update filter
            self._store.clear()
            for issue, local in self._issues:
                self.__append_issue_filtered(issue, local)

    def __on_tasks_toggled(self, togglebutton):
        self._show_tasks = togglebutton.get_active()
        self._preferences.set("IssuesShowTasks", self._show_tasks)

    def __on_warnings_toggled(self, togglebutton):
        self._show_warnings = togglebutton.get_active()
        self._preferences.set("IssuesShowWarnings", self._show_warnings)

    def clear(self):
        """
		Remove all issues from the view
		"""
        self.assure_init()
        self._store.clear()
        self._issues = []

    def append_issue(self, issue, local=True):
        """
		Append a new Issue to the view

		@param issue: the Issue object
		@param local: indicates whether the Issue occured in the edited file or not
		"""
        self.assure_init()
        self._issues.append((issue, local))
        self.__append_issue_filtered(issue, local)

    def __append_issue_filtered(self, issue, local):
        if issue.severity == Issue.SEVERITY_WARNING:
            if self._show_warnings:
                self.__do_append_issue(issue, local)
        elif issue.severity == Issue.SEVERITY_TASK:
            if self._show_tasks:
                self.__do_append_issue(issue, local)
        else:
            self.__do_append_issue(issue, local)

    def __do_append_issue(self, issue, local):
        if local:
            message = issue.message
            filename = escape(issue.file.basename)
        else:
            message = "<span color='%s'>%s</span>" % (self._preferences.get(
                "LightForeground", "#7f7f7f"), issue.message)
            filename = "<span color='%s'>%s</span>" % (self._preferences.get(
                "LightForeground", "#7f7f7f"), issue.file.basename)
        self._store.append(
            [self._icons[issue.severity], message, filename, issue])

    def destroy(self):
        del self._editor
        self._preferences.remove_monitor(self)
        for obj in self._handlers:
            obj.disconnect(self._handlers[obj])
        BottomView.destroy(self)
예제 #5
0
class IssueView(PanelView):
    """
    """

    _log = getLogger("IssueView")

    def __init__(self, context, editor):
        PanelView.__init__(self, context)
        self._log.debug("init")

        self._editor = editor
        self._handlers = {}
        self._preferences = Preferences()

        self._preferences.connect("preferences-changed", self._on_preferences_changed)
        self._show_tasks = self._preferences.get("issues-show-tasks")
        self._show_warnings = self._preferences.get("issues-show-warnings")

        self._icons = { Issue.SEVERITY_WARNING : GdkPixbuf.Pixbuf.new_from_file(Resources().get_icon("warning.png")),
                        Issue.SEVERITY_ERROR : GdkPixbuf.Pixbuf.new_from_file(Resources().get_icon("error.png")),
                        Issue.SEVERITY_INFO : None,
                        Issue.SEVERITY_TASK : GdkPixbuf.Pixbuf.new_from_file(Resources().get_icon("task.png")) }

        grid = Gtk.Grid()
        self.add(grid)

        self._store = Gtk.ListStore(GdkPixbuf.Pixbuf, str, str, object)

        self._view = Gtk.TreeView(model=self._store)

        column = Gtk.TreeViewColumn()
        column.set_title(_("Message"))

        pixbuf_renderer = Gtk.CellRendererPixbuf()
        column.pack_start(pixbuf_renderer, False)
        column.add_attribute(pixbuf_renderer, "pixbuf", 0)

        text_renderer = Gtk.CellRendererText()
        column.pack_start(text_renderer, True)
        column.add_attribute(text_renderer, "markup", 1)

        self._view.append_column(column)

        column = Gtk.TreeViewColumn()
        column.set_title(_("File"))
        text_renderer2 = Gtk.CellRendererText()
        column.pack_start(text_renderer2, True)
        column.add_attribute(text_renderer2, "markup", 2)
        self._view.insert_column(column, -1)
        self._handlers[self._view] = self._view.connect("row-activated", self._on_row_activated)

        self._scr = Gtk.ScrolledWindow()

        self._scr.add(self._view)
        self._scr.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        self._scr.set_shadow_type(Gtk.ShadowType.IN)
        self._scr.set_hexpand(True)
        self._scr.set_vexpand(True)

        grid.add(self._scr)

        # toolbar
        self._button_warnings = Gtk.ToggleToolButton()
        self._button_warnings.set_tooltip_text(_("Show/Hide Warnings"))
        image = Gtk.Image()
        image.set_from_file(Resources().get_icon("warning.png"))
        self._button_warnings.set_icon_widget(image)
        self._button_warnings.set_active(self._show_warnings)
        self._handlers[self._button_warnings] = self._button_warnings.connect("toggled", self.__on_warnings_toggled)

        self._button_tasks = Gtk.ToggleToolButton()
        self._button_tasks.set_tooltip_text(_("Show/Hide Tasks"))
        imageTask = Gtk.Image()
        imageTask.set_from_file(Resources().get_icon("task.png"))
        self._button_tasks.set_icon_widget(imageTask)
        self._button_tasks.set_active(self._show_tasks)
        self._handlers[self._button_tasks] = self._button_tasks.connect("toggled", self.__on_tasks_toggled)

        toolbar = Gtk.Toolbar()
        toolbar.set_orientation(Gtk.Orientation.VERTICAL)
        toolbar.set_style(Gtk.ToolbarStyle.ICONS)
        toolbar.set_icon_size(Gtk.IconSize.MENU)
        toolbar.insert(self._button_warnings, -1)
        toolbar.insert(self._button_tasks, -1)
        toolbar.set_vexpand(True)

        grid.add(toolbar)

        # theme like gtk3
        ctx = self._scr.get_style_context()
        ctx.set_junction_sides(Gtk.JunctionSides.RIGHT)

        ctx = toolbar.get_style_context()
        ctx.set_junction_sides(Gtk.JunctionSides.LEFT | Gtk.JunctionSides.RIGHT)
        ctx.add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)

        self._issues = []

        self.show_all()

        self._log.debug("init finished")

    def get_label(self):
        return _("Issues")

    def get_icon(self):
        return Gtk.Image.new_from_stock(Gtk.STOCK_DIALOG_INFO, Gtk.IconSize.MENU)

    def _on_row_activated(self, view, path, column):
        """
        A row has been double-clicked on
        """
        issue = self._store.get(self._store.get_iter(path), 3)[0]

        self._context.activate_editor(issue.file)

        #~ # FIXME: this doesn't work correctly
        #~ if not self._context.active_editor is None:
            #~ self._context.active_editor.select(issue.start, issue.end)
        self._editor.select(issue.start, issue.end)

    def _on_preferences_changed(self, prefs, key, value):
        if key == "issues-show-warnings" or key == "issues-show-tasks":
            # update filter
            self._store.clear()
            for issue, local in self._issues:
                self._append_issue_filtered(issue, local)

    def __on_tasks_toggled(self, togglebutton):
        self._show_tasks = togglebutton.get_active()
        self._preferences.set("issues-show-tasks", self._show_tasks)

    def __on_warnings_toggled(self, togglebutton):
        self._show_warnings = togglebutton.get_active()
        self._preferences.set("issues-show-warnings", self._show_warnings)

    def clear(self):
        """
        Remove all issues from the view
        """
        self._store.clear()
        self._issues = []

    def append_issue(self, issue, local=True):
        """
        Append a new Issue to the view

        @param issue: the Issue object
        @param local: indicates whether the Issue occured in the edited file or not
        """
        self._issues.append((issue, local))
        self._append_issue_filtered(issue, local)

    def _append_issue_filtered(self, issue, local):
        if issue.severity == Issue.SEVERITY_WARNING:
            if self._show_warnings:
                self._do_append_issue(issue, local)
        elif issue.severity == Issue.SEVERITY_TASK:
            if self._show_tasks:
                self._do_append_issue(issue, local)
        else:
            self._do_append_issue(issue, local)

    def _do_append_issue(self, issue, local):
        if local:
            message = issue.message
            filename = escape(issue.file.basename)
        else:
            message = "<span color='%s'>%s</span>" % (self._preferences.get("light-foreground-color"), issue.message)
            filename = "<span color='%s'>%s</span>" % (self._preferences.get("light-foreground-color"), issue.file.basename)
        self._store.append([self._icons[issue.severity], message, filename, issue])
예제 #6
0
class BaseOutlineView(PanelView):
    """
    Base class for the BibTeX and LaTeX outline views
    """

    __log = getLogger("BaseOutlineView")

    def __init__(self, context, editor):
        PanelView.__init__(self, context)
        self._editor = editor
        self._base_handlers = {}

        self.set_orientation(Gtk.Orientation.VERTICAL)

        self._preferences = Preferences()

        grid = Gtk.Grid()
        grid.set_orientation(Gtk.Orientation.VERTICAL)
        self.add(grid)

        # toolbar

        btn_follow = Gtk.ToggleToolButton.new_from_stock(Gtk.STOCK_CONNECT)
        btn_follow.set_tooltip_text(_("Follow Editor"))
        btn_follow.set_active(
            self._preferences.get("outline-connect-to-editor"))
        self._base_handlers[btn_follow] = btn_follow.connect(
            "toggled", self._on_follow_toggled)

        btn_expand = Gtk.ToolButton.new_from_stock(Gtk.STOCK_ZOOM_IN)
        btn_expand.set_tooltip_text(_("Expand All"))
        self._base_handlers[btn_expand] = btn_expand.connect(
            "clicked", self._on_expand_clicked)

        btn_collapse = Gtk.ToolButton.new_from_stock(Gtk.STOCK_ZOOM_OUT)
        btn_collapse.set_tooltip_text(_("Collapse All"))
        self._base_handlers[btn_collapse] = btn_collapse.connect(
            "clicked", self._on_collapse_clicked)

        self._toolbar = Gtk.Toolbar()
        self._toolbar.set_style(Gtk.ToolbarStyle.ICONS)
        self._toolbar.set_icon_size(Gtk.IconSize.MENU)
        self._toolbar.insert(btn_follow, -1)
        self._toolbar.insert(Gtk.SeparatorToolItem(), -1)
        self._toolbar.insert(btn_expand, -1)
        self._toolbar.insert(btn_collapse, -1)
        self._toolbar.insert(Gtk.SeparatorToolItem(), -1)
        self._toolbar.set_hexpand(True)

        grid.add(self._toolbar)

        # tree view

        column = Gtk.TreeViewColumn()

        pixbuf_renderer = Gtk.CellRendererPixbuf()
        column.pack_start(pixbuf_renderer, False)
        column.add_attribute(pixbuf_renderer, "pixbuf", 1)

        text_renderer = Gtk.CellRendererText()
        column.pack_start(text_renderer, True)
        column.add_attribute(text_renderer, "markup", 0)

        self._offset_map = OutlineOffsetMap()

        self._store = Gtk.TreeStore(str, GdkPixbuf.Pixbuf,
                                    object)  # label, icon, node object

        self._view = Gtk.TreeView(model=self._store)
        self._view.append_column(column)
        self._view.set_headers_visible(False)
        self._cursor_changed_id = self._view.connect("cursor-changed",
                                                     self._on_cursor_changed)
        self._base_handlers[self._view] = self._view.connect(
            "row-activated", self._on_row_activated)

        scrolled = Gtk.ScrolledWindow()
        scrolled.add(self._view)
        scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scrolled.set_vexpand(True)

        grid.add(scrolled)

        # this holds a list of the currently expanded paths
        self._expandedPaths = None

    def get_label(self):
        return _("Outline")

    def get_icon(self):
        return Gtk.Image.new_from_file(Resources().get_icon("outline.png"))

    def _on_follow_toggled(self, toggle_button):
        value = toggle_button.get_active()
        self._preferences.set("outline-connect-to-editor", value)

    def _on_expand_clicked(self, button):
        self._view.expand_all()

    def _on_collapse_clicked(self, button):
        self._view.collapse_all()

    def select_path_by_offset(self, offset):
        """
        Select the path corresponding to a given offset in the source

        Called by the Editor
        """
        try:
            path = self._offset_map.lookup(offset)
            self._select_path(path)
        except KeyError:
            pass

    def _save_state(self):
        """
        Save the current expand state
        """
        self._expanded_paths = []
        self._view.map_expanded_rows(self._save_state_map_function, None)

    def _save_state_map_function(self, view, path, user_data=None):
        """
        Mapping function for saving the current expand state
        """
        self._expanded_paths.append(path.to_string())

    def _restore_state(self):
        """
        Restore the last expand state
        """
        self._view.collapse_all()

        if self._expanded_paths:
            for path in self._expanded_paths:
                self._view.expand_to_path(Gtk.TreePath.new_from_string(path))

    def _on_cursor_changed(self, view):
        selection = view.get_selection()
        if not selection:
            return

        store, it = selection.get_selected()
        if not it:
            return

        outline_node = store.get_value(it, 2)
        self._on_node_selected(outline_node)

    def _on_row_activated(self, view, path, column):
        it = self._store.get_iter(path)
        node = self._store.get(it, 2)[0]

        self._on_node_activated(node)

    def _select_path(self, path):
        """
        Expand a path and select the last node
        """
        selection = self._view.get_selection()
        if not selection:
            return

        # select path
        self._view.expand_to_path(path)
        selection.select_path(path)

    #
    # methods to be overridden by the subclass
    #

    def _on_node_selected(self, node):
        """
        To be overridden
        """

    def _on_node_activated(self, node):
        """
        To be overridden
        """

    def set_outline(self, outline):
        """
예제 #7
0
파일: outline.py 프로젝트: Sbte/gedit-latex
class BaseOutlineView(PanelView):
    """
    Base class for the BibTeX and LaTeX outline views
    """

    __log = getLogger("BaseOutlineView")

    def __init__(self, context, editor):
        PanelView.__init__(self, context)
        self._editor = editor
        self._base_handlers = {}

        self.set_orientation(Gtk.Orientation.VERTICAL)

        self._preferences = Preferences()

        grid = Gtk.Grid()
        grid.set_orientation(Gtk.Orientation.VERTICAL)
        self.add(grid)

        # toolbar

        btn_follow = Gtk.ToggleToolButton.new_from_stock(Gtk.STOCK_CONNECT)
        btn_follow.set_tooltip_text(_("Follow Editor"))
        btn_follow.set_active(self._preferences.get("outline-connect-to-editor"))
        self._base_handlers[btn_follow] = btn_follow.connect("toggled", self._on_follow_toggled)

        btn_expand = Gtk.ToolButton.new_from_stock(Gtk.STOCK_ZOOM_IN)
        btn_expand.set_tooltip_text(_("Expand All"))
        self._base_handlers[btn_expand] = btn_expand.connect("clicked", self._on_expand_clicked)

        btn_collapse = Gtk.ToolButton.new_from_stock(Gtk.STOCK_ZOOM_OUT)
        btn_collapse.set_tooltip_text(_("Collapse All"))
        self._base_handlers[btn_collapse] = btn_collapse.connect("clicked", self._on_collapse_clicked)

        self._toolbar = Gtk.Toolbar()
        self._toolbar.set_style(Gtk.ToolbarStyle.ICONS)
        self._toolbar.set_icon_size(Gtk.IconSize.MENU)
        self._toolbar.insert(btn_follow, -1)
        self._toolbar.insert(Gtk.SeparatorToolItem(), -1)
        self._toolbar.insert(btn_expand, -1)
        self._toolbar.insert(btn_collapse, -1)
        self._toolbar.insert(Gtk.SeparatorToolItem(), -1)
        self._toolbar.set_hexpand(True)

        grid.add(self._toolbar)

        # tree view

        column = Gtk.TreeViewColumn()

        pixbuf_renderer = Gtk.CellRendererPixbuf()
        column.pack_start(pixbuf_renderer, False)
        column.add_attribute(pixbuf_renderer, "pixbuf", 1)

        text_renderer = Gtk.CellRendererText()
        column.pack_start(text_renderer, True)
        column.add_attribute(text_renderer, "markup", 0)

        self._offset_map = OutlineOffsetMap()

        self._store = Gtk.TreeStore(str, GdkPixbuf.Pixbuf, object)    # label, icon, node object

        self._view = Gtk.TreeView(model=self._store)
        self._view.append_column(column)
        self._view.set_headers_visible(False)
        self._cursor_changed_id = self._view.connect("cursor-changed", self._on_cursor_changed)
        self._base_handlers[self._view] = self._view.connect("row-activated", self._on_row_activated)

        scrolled = Gtk.ScrolledWindow()
        scrolled.add(self._view)
        scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scrolled.set_vexpand(True)

        grid.add(scrolled)

        # this holds a list of the currently expanded paths
        self._expandedPaths = None

    def get_label(self):
        return _("Outline")

    def get_icon(self):
        return Gtk.Image.new_from_file(Resources().get_icon("outline.png"))

    def _on_follow_toggled(self, toggle_button):
        value = toggle_button.get_active()
        self._preferences.set("outline-connect-to-editor", value)

    def _on_expand_clicked(self, button):
        self._view.expand_all()

    def _on_collapse_clicked(self, button):
        self._view.collapse_all()

    def select_path_by_offset(self, offset):
        """
        Select the path corresponding to a given offset in the source

        Called by the Editor
        """
        try:
            path = self._offset_map.lookup(offset)
            self._select_path(path)
        except KeyError:
            pass

    def _save_state(self):
        """
        Save the current expand state
        """
        self._expanded_paths = []
        self._view.map_expanded_rows(self._save_state_map_function,None)

    def _save_state_map_function(self, view, path, user_data=None):
        """
        Mapping function for saving the current expand state
        """
        self._expanded_paths.append(path.to_string())

    def _restore_state(self):
        """
        Restore the last expand state
        """
        self._view.collapse_all()

        if self._expanded_paths:
            for path in self._expanded_paths:
                self._view.expand_to_path(Gtk.TreePath.new_from_string(path))

    def _on_cursor_changed(self, view):
        selection = view.get_selection()
        if not selection:
            return

        store, it = selection.get_selected()
        if not it:
            return

        outline_node = store.get_value(it, 2)
        self._on_node_selected(outline_node)

    def _on_row_activated(self, view, path, column):
        it = self._store.get_iter(path)
        node = self._store.get(it, 2)[0]

        self._on_node_activated(node)

    def _select_path(self, path):
        """
        Expand a path and select the last node
        """
        selection = self._view.get_selection()
        if not selection:
            return

        # select path
        self._view.expand_to_path(path)
        selection.select_path(path)

    #
    # methods to be overridden by the subclass
    #

    def _on_node_selected(self, node):
        """
        To be overridden
        """

    def _on_node_activated(self, node):
        """
        To be overridden
        """

    def set_outline(self, outline):
        """
예제 #8
0
class Game:
    def __init__(self):
        pygame.init()

        #get preferences
        self.preferences = Preferences()
        # self.nickname = raw_input('Choose a username: '******'Choose a color (red, green, blue, yellow, white): ')
        #resolution, flags, depth, display
        self.unit=Constants.RESOLUTION[0]/Constants.UNITS
        self.banner = Banner()
        self.score_width=self.unit*15

        if self.preferences.fullscreen:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),pygame.FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),0,32)

        pygame.display.set_caption(Constants.CAPTION)

        #game area surface
        self.gamescreen = pygame.Surface(Constants.RESOLUTION)
        #score area rectangle surface
        self.scorescreen = pygame.Surface((self.score_width,Constants.RESOLUTION[1]))

        #Snake and foods manager
        self.me=Snake(color=pygame.color.THECOLORS[self.preferences.get("color")],\
                    nickname=self.preferences.get("nickname"))


        self.f=Foods()

        self.others = {}

        #Score manager
        self.scores=Scores((self.score_width,Constants.RESOLUTION[1]))

        #add our own score, the server will send us the remaining one at connection
        self.scores.new_score(self.preferences.get("nickname"),\
                        pygame.color.THECOLORS[self.preferences.get("color")])

	#game area background color
        self.gamescreen.fill(Constants.COLOR_BG)
        self.scorescreen.fill((100,100,100))

        #timers
        self.clock=pygame.time.Clock();
        self.current_time=0

        self.move_snake_timer=Timer(1.0/Constants.SNAKE_SPEED*1000,self.current_time,periodic=True)
        self.blink_snake_timer=Timer(1.0/Constants.SNAKE_BLINKING_SPEED*1000,self.current_time,periodic=True)
        self.blink_banner_timer=Timer(500,self.current_time,periodic=True)
        self.new_apple_timer=Timer(Constants.NEW_APPLE_PERIOD*1000,self.current_time,periodic=True)



    def process_events(self):
        #key handling
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                   self.running=False
                if event.key == pygame.K_UP:
                   self.me.action(1)
                if event.key == pygame.K_DOWN:
                   self.me.action(2)
                if event.key == pygame.K_LEFT:
                   self.me.action(3)
                if event.key == pygame.K_RIGHT:
                   self.me.action(4)
                if event.key == pygame.K_SPACE:
                   #self.me.set_ready()
                   self.com.sendSecure("{\"ready\": true}", self.address)
    def run(self):

        self.address = (self.preferences.get("server"), self.preferences.get("port"))

        #initialisation du snakePost
        self.client = SnakeChan()

        self.client.connect(self.address, self.preferences.get("color"), self.preferences.get("nickname"))
        self.com = SnakePost(self.client, self.preferences.get("nickname"))


        whole_second=0
        self.running=True
        while self.running:
            #time tracking
            self.current_time+=self.clock.tick(Constants.FPS)

            #check if the snake is still alive
            if not self.me.alive:
                self.me.alive=True
                self.me.restart()

            #check if game need more food
            # if self.new_apple_timer.expired(self.current_time):
            #     self.f.make()

            #check if we need to move our own snake's state
            #if we do, send an update of our position to
            #the server
            if self.move_snake_timer.expired(self.current_time):
                self.me.move()
                pos = self.me.netinfo()
                self.com.send(pos, self.address)

            #check if we need to blink the unready snakes (unready state)
            if self.blink_snake_timer.expired(self.current_time):
                for snake in self.others:
                    self.others[snake].blink()

            #cleanup background
            self.gamescreen.fill(Constants.COLOR_BG)

            #draw scores
            self.scores.draw(self.screen)

            #draw all snakes positions as last seen by the server
            #we do not compute their positions ourselves!

            for snake in self.others:
                self.others[snake].draw(self.gamescreen)

            #draw food
            self.f.draw(self.gamescreen)

            #process external events (keyboard,...)
            self.process_events()

            #then update display
            #update game area on screen container
            self.screen.blit(self.gamescreen,(self.score_width,0))

            pygame.display.update()

            # Sur message du serveur...
            data, addr = self.com.listen()

            if data is not None:

                dat = json.loads(data)

                for key in dat:

                    if key == 'players_info':
                        #On met a jour les scores et les etats des joueurs
                        for player in dat[key]:

                            if not self.others.get(player[0]): # Si on a pas de joueur de ce nom, on l'ajoute
                                self.others[player[0]] = Snake(color=pygame.color.THECOLORS[player[1]], nickname=player[0])
                                self.scores.new_score(player[0], self.others.get(player[0]).color)

                            else: # On a deja le joueur, on update son etat
                                if player[3]:
                                    self.others[player[0]].set_ready()
                                else:
                                    self.others[player[0]].set_unready()
                            # on update les scores
                            self.scores.set_score(player[0], player[2])

                    elif key == "snakes": # message de position des joueurs

                        # on regarde si il y a des serpents a enlever
                        if len(dat[key]) != len(self.others):
                            for nickname in self.others.keys():
                                connected = False
                                for val in dat[key]:
                                    if val[0] == nickname:
                                        connected = True
                                if not connected:
                                    del self.others[nickname]
                                    self.scores.del_score(nickname)

                        for val in dat[key]:
                            # si on a ce joeur et que ses positions ne sont pas vides (premier message)
                            if len(val[1]) > 0 and self.others[val[0]]:
                                self.others[val[0]].setBody(val[1])

                    elif key == "foods": # les pommes envoyees par le serveur
                        self.f.set_positions(dat[key])

                    elif key == "grow": # Un serpent a mange une pomme !
                        if dat[key] == self.preferences.get("nickname"):
                            self.me.grow(Constants.GROW)

                    elif key == "game_over": # Desole, c'est perdu
                        if dat[key] == self.preferences.get("nickname"):
                            self.me.restart()
예제 #9
0
class Game:
    def __init__(self):
        pygame.init()
        
        #get preferences
        self.preferences = Preferences() 

        #resolution, flags, depth, display
        self.unit=Constants.RESOLUTION[0]/Constants.UNITS
        self.banner = Banner()
        self.score_width=self.unit*15

        if self.preferences.fullscreen:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),pygame.FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),0,32)
        
        pygame.display.set_caption(Constants.CAPTION)
        
        #game area surface
        self.gamescreen = pygame.Surface(Constants.RESOLUTION)
        #score area rectangle surface
        self.scorescreen = pygame.Surface((self.score_width,Constants.RESOLUTION[1]))

        #Snake and foods manager 
        self.me=Snake(color=pygame.color.THECOLORS[self.preferences.get("color")],\
                     nickname=self.preferences.get("nickname"))
        
        self.nickname = self.preferences.get("nickname")
        self.f=Foods()

        #Score manager
        self.scores=Scores((self.score_width,Constants.RESOLUTION[1]))
        
        #add our own score, the server will send us the remaining one at connection
        self.scores.new_score(self.preferences.get("nickname"),\
                        pygame.color.THECOLORS[self.preferences.get("color")])

	#game area background color
        self.gamescreen.fill(Constants.COLOR_BG)
        self.scorescreen.fill((100,100,100))
        
        #timers
        self.clock=pygame.time.Clock();
        self.current_time=0
        
        self.move_snake_timer=Timer(1.0/Constants.SNAKE_SPEED*1000,self.current_time,periodic=True)
        self.blink_snake_timer=Timer(1.0/Constants.SNAKE_BLINKING_SPEED*1000,self.current_time,periodic=True)
        self.blink_banner_timer=Timer(500,self.current_time,periodic=True)
        self.new_apple_timer=Timer(Constants.NEW_APPLE_PERIOD*1000,self.current_time,periodic=True)

    def process_events(self):
        #key handling
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                   self.running=False 
                if event.key == pygame.K_UP:
                   self.me.action(1)
                if event.key == pygame.K_DOWN:
                   self.me.action(2)
                if event.key == pygame.K_LEFT:
                   self.me.action(3)
                if event.key == pygame.K_RIGHT:
                   self.me.action(4)
                if event.key == pygame.K_SPACE:
                   self.me.set_ready()

    def run(self):
        whole_second=0
        self.running=True
        while self.running:
            #time tracking
            self.current_time+=self.clock.tick(Constants.FPS) 
          
            #check if the snake is still alive
            if not self.me.alive:
                self.me.alive=True
                self.me.restart()

            #check if game need more food
            if self.new_apple_timer.expired(self.current_time):
                self.f.make()

            #check if we need to move our own snake's state
            #if we do, send an update of our position to 
            #the server
            if self.move_snake_timer.expired(self.current_time):
                self.me.move()

            #check if we need to blink the unready snakes (unready state)
            if self.blink_snake_timer.expired(self.current_time):
                self.me.blink()

            #check if snake has eaten
            if self.me.ready:
                if self.f.check(self.me.head):
                    self.me.grow(Constants.GROW)
                    self.scores.inc_score(self.nickname,1)

            #cleanup background
            self.gamescreen.fill(Constants.COLOR_BG)
            
            #draw scores
            self.scores.draw(self.screen)
            
            #draw all snakes positions as last seen by the server
            #we do not compute their positions ourselves!
            self.me.draw(self.gamescreen) 
                
            #draw food
            self.f.draw(self.gamescreen)
            
            #process external events (keyboard,...)
            self.process_events()

            #then update display
            #update game area on screen container
            self.screen.blit(self.gamescreen,(self.score_width,0)) 
	    
            pygame.display.update()
예제 #10
0
class IssueView(BottomView, IPreferencesMonitor):
	"""
	"""

	_log = getLogger("IssueView")

	label = "Issues"
	icon = gtk.STOCK_DIALOG_INFO
	scope = View.SCOPE_EDITOR

	def __init__(self, context, editor):
		BottomView.__init__(self, context)
		self._editor = editor
		self._handlers = {}

	def init(self, context):
		self._log.debug("init")

		self._preferences = Preferences()
		self._show_tasks = self._preferences.get_bool("IssuesShowTasks", True)
		self._show_warnings = self._preferences.get_bool("IssuesShowWarnings", True)

		self._context = context

		self._icons = { Issue.SEVERITY_WARNING : pixbuf_new_from_file(find_resource("icons/warning.png")),
						Issue.SEVERITY_ERROR : pixbuf_new_from_file(find_resource("icons/error.png")),
						Issue.SEVERITY_INFO : None,
						Issue.SEVERITY_TASK : pixbuf_new_from_file(find_resource("icons/task.png")) }

		self._store = gtk.ListStore(Pixbuf, str, str, object)

		self._view = gtk.TreeView(self._store)

		column = gtk.TreeViewColumn()
		column.set_title("Message")

		pixbuf_renderer = gtk.CellRendererPixbuf()
		column.pack_start(pixbuf_renderer, False)
		column.add_attribute(pixbuf_renderer, "pixbuf", 0)

		text_renderer = gtk.CellRendererText()
		column.pack_start(text_renderer, True)
		column.add_attribute(text_renderer, "markup", 1)

		self._view.append_column(column)
		self._view.insert_column_with_attributes(-1, "File", gtk.CellRendererText(), markup=2)
		self._handlers[self._view] = self._view.connect("row-activated", self._on_row_activated)

		self._scr = gtk.ScrolledWindow()

		self._scr.add(self._view)
		self._scr.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		self._scr.set_shadow_type(gtk.SHADOW_IN)

		self.pack_start(self._scr, True)

		# toolbar

		self._button_warnings = gtk.ToggleToolButton()
		self._button_warnings.set_tooltip_text("Show/Hide Warnings")
		image = gtk.Image()
		image.set_from_file(find_resource("icons/warning.png"))
		self._button_warnings.set_icon_widget(image)
		self._button_warnings.set_active(self._show_warnings)
		self._handlers[self._button_warnings] = self._button_warnings.connect("toggled", self.__on_warnings_toggled)

		self._button_tasks = gtk.ToggleToolButton()
		self._button_tasks.set_tooltip_text("Show/Hide Tasks")
		imageTask = gtk.Image()
		imageTask.set_from_file(find_resource("icons/task.png"))
		self._button_tasks.set_icon_widget(imageTask)
		self._button_tasks.set_active(self._show_tasks)
		self._handlers[self._button_tasks] = self._button_tasks.connect("toggled", self.__on_tasks_toggled)

		toolbar = gtk.Toolbar()
		toolbar.set_orientation(gtk.ORIENTATION_VERTICAL)
		toolbar.set_style(gtk.TOOLBAR_ICONS)
		toolbar.set_icon_size(gtk.ICON_SIZE_MENU)
		toolbar.insert(self._button_warnings, -1)
		toolbar.insert(self._button_tasks, -1)

		self.pack_start(toolbar, False)

		self._issues = []
		self._preferences.register_monitor(self)

		self._log.debug("init finished")

	def _on_row_activated(self, view, path, column):
		"""
		A row has been double-clicked on
		"""
		issue = self._store.get(self._store.get_iter(path), 3)[0]

		self._context.activate_editor(issue.file)

		#~ # FIXME: this doesn't work correctly
		#~ if not self._context.active_editor is None:
			#~ self._context.active_editor.select(issue.start, issue.end)
		self._editor.select(issue.start, issue.end)

	def _on_value_changed(self, key, value):
		if key == "IssuesShowWarnings" or key == "IssuesShowTasks":
			# update filter
			self._store.clear()
			for issue, local in self._issues:
				self.__append_issue_filtered(issue, local)

	def __on_tasks_toggled(self, togglebutton):
		self._show_tasks = togglebutton.get_active()
		self._preferences.set("IssuesShowTasks", self._show_tasks)

	def __on_warnings_toggled(self, togglebutton):
		self._show_warnings = togglebutton.get_active()
		self._preferences.set("IssuesShowWarnings", self._show_warnings)

	def clear(self):
		"""
		Remove all issues from the view
		"""
		self.assure_init()
		self._store.clear()
		self._issues = []

	def append_issue(self, issue, local=True):
		"""
		Append a new Issue to the view

		@param issue: the Issue object
		@param local: indicates whether the Issue occured in the edited file or not
		"""
		self.assure_init()
		self._issues.append((issue, local))
		self.__append_issue_filtered(issue, local)

	def __append_issue_filtered(self, issue, local):
		if issue.severity == Issue.SEVERITY_WARNING:
			if self._show_warnings:
				self.__do_append_issue(issue, local)
		elif issue.severity == Issue.SEVERITY_TASK:
			if self._show_tasks:
				self.__do_append_issue(issue, local)
		else:
			self.__do_append_issue(issue, local)

	def __do_append_issue(self, issue, local):
		if local:
			message = issue.message
			filename = escape(issue.file.basename)
		else:
			message = "<span color='%s'>%s</span>" % (self._preferences.get("LightForeground", "#7f7f7f"), issue.message)
			filename = "<span color='%s'>%s</span>" % (self._preferences.get("LightForeground", "#7f7f7f"), issue.file.basename)
		self._store.append([self._icons[issue.severity], message, filename, issue])

	def destroy(self):
		del self._editor
		self._preferences.remove_monitor(self)
		for obj in self._handlers:
			obj.disconnect(self._handlers[obj])
		BottomView.destroy(self)
예제 #11
0
class Game:
    def __init__(self):
        pygame.init()

        #get preferences
        self.preferences = Preferences()
        # self.nickname = raw_input('Choose a username: '******'Choose a color (red, green, blue, yellow, white): ')
        #resolution, flags, depth, display
        self.unit = Constants.RESOLUTION[0] / Constants.UNITS
        self.banner = Banner()
        self.score_width = self.unit * 15

        if self.preferences.fullscreen:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),pygame.FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode((Constants.RESOLUTION[0]+self.score_width,\
                                               Constants.RESOLUTION[1]),0,32)

        pygame.display.set_caption(Constants.CAPTION)

        #game area surface
        self.gamescreen = pygame.Surface(Constants.RESOLUTION)
        #score area rectangle surface
        self.scorescreen = pygame.Surface(
            (self.score_width, Constants.RESOLUTION[1]))

        #Snake and foods manager
        self.me=Snake(color=pygame.color.THECOLORS[self.preferences.get("color")],\
                    nickname=self.preferences.get("nickname"))

        self.f = Foods()

        self.others = {}

        #Score manager
        self.scores = Scores((self.score_width, Constants.RESOLUTION[1]))

        #add our own score, the server will send us the remaining one at connection
        self.scores.new_score(self.preferences.get("nickname"),\
                        pygame.color.THECOLORS[self.preferences.get("color")])

        #game area background color
        self.gamescreen.fill(Constants.COLOR_BG)
        self.scorescreen.fill((100, 100, 100))

        #timers
        self.clock = pygame.time.Clock()
        self.current_time = 0

        self.move_snake_timer = Timer(1.0 / Constants.SNAKE_SPEED * 1000,
                                      self.current_time,
                                      periodic=True)
        self.blink_snake_timer = Timer(1.0 / Constants.SNAKE_BLINKING_SPEED *
                                       1000,
                                       self.current_time,
                                       periodic=True)
        self.blink_banner_timer = Timer(500, self.current_time, periodic=True)
        self.new_apple_timer = Timer(Constants.NEW_APPLE_PERIOD * 1000,
                                     self.current_time,
                                     periodic=True)

    def process_events(self):
        #key handling
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                if event.key == pygame.K_UP:
                    self.me.action(1)
                if event.key == pygame.K_DOWN:
                    self.me.action(2)
                if event.key == pygame.K_LEFT:
                    self.me.action(3)
                if event.key == pygame.K_RIGHT:
                    self.me.action(4)
                if event.key == pygame.K_SPACE:
                    #self.me.set_ready()
                    self.com.sendSecure("{\"ready\": true}", self.address)

    def run(self):

        self.address = (self.preferences.get("server"),
                        self.preferences.get("port"))

        #initialisation du snakePost
        self.client = SnakeChan()

        self.client.connect(self.address, self.preferences.get("color"),
                            self.preferences.get("nickname"))
        self.com = SnakePost(self.client, self.preferences.get("nickname"))

        whole_second = 0
        self.running = True
        while self.running:
            #time tracking
            self.current_time += self.clock.tick(Constants.FPS)

            #check if the snake is still alive
            if not self.me.alive:
                self.me.alive = True
                self.me.restart()

            #check if game need more food
            # if self.new_apple_timer.expired(self.current_time):
            #     self.f.make()

            #check if we need to move our own snake's state
            #if we do, send an update of our position to
            #the server
            if self.move_snake_timer.expired(self.current_time):
                self.me.move()
                pos = self.me.netinfo()
                self.com.send(pos, self.address)

            #check if we need to blink the unready snakes (unready state)
            if self.blink_snake_timer.expired(self.current_time):
                for snake in self.others:
                    self.others[snake].blink()

            #cleanup background
            self.gamescreen.fill(Constants.COLOR_BG)

            #draw scores
            self.scores.draw(self.screen)

            #draw all snakes positions as last seen by the server
            #we do not compute their positions ourselves!

            for snake in self.others:
                self.others[snake].draw(self.gamescreen)

            #draw food
            self.f.draw(self.gamescreen)

            #process external events (keyboard,...)
            self.process_events()

            #then update display
            #update game area on screen container
            self.screen.blit(self.gamescreen, (self.score_width, 0))

            pygame.display.update()

            # Sur message du serveur...
            data, addr = self.com.listen()

            if data is not None:

                dat = json.loads(data)

                for key in dat:

                    if key == 'players_info':
                        #On met a jour les scores et les etats des joueurs
                        for player in dat[key]:

                            if not self.others.get(
                                    player[0]
                            ):  # Si on a pas de joueur de ce nom, on l'ajoute
                                self.others[player[0]] = Snake(
                                    color=pygame.color.THECOLORS[player[1]],
                                    nickname=player[0])
                                self.scores.new_score(
                                    player[0],
                                    self.others.get(player[0]).color)

                            else:  # On a deja le joueur, on update son etat
                                if player[3]:
                                    self.others[player[0]].set_ready()
                                else:
                                    self.others[player[0]].set_unready()
                            # on update les scores
                            self.scores.set_score(player[0], player[2])

                    elif key == "snakes":  # message de position des joueurs

                        # on regarde si il y a des serpents a enlever
                        if len(dat[key]) != len(self.others):
                            for nickname in self.others.keys():
                                connected = False
                                for val in dat[key]:
                                    if val[0] == nickname:
                                        connected = True
                                if not connected:
                                    del self.others[nickname]
                                    self.scores.del_score(nickname)

                        for val in dat[key]:
                            # si on a ce joeur et que ses positions ne sont pas vides (premier message)
                            if len(val[1]) > 0 and self.others[val[0]]:
                                self.others[val[0]].setBody(val[1])

                    elif key == "foods":  # les pommes envoyees par le serveur
                        self.f.set_positions(dat[key])

                    elif key == "grow":  # Un serpent a mange une pomme !
                        if dat[key] == self.preferences.get("nickname"):
                            self.me.grow(Constants.GROW)

                    elif key == "game_over":  # Desole, c'est perdu
                        if dat[key] == self.preferences.get("nickname"):
                            self.me.restart()