Beispiel #1
0
class Stator():
    """ Create a sprite for a stator """
    def __init__(self, sprites, path, name, x, y, w, h, svg_engine=None,
                 calculate=None, result=None):
        if svg_engine is None:
            self.spr = Sprite(sprites, x, y, file_to_pixbuf(path, name, w, h))
        else:
            self.spr = Sprite(sprites, x, y,
                              svg_str_to_pixbuf(svg_engine().svg))
        self.spr.type = name
        self.name = name
        self.calculate = calculate
        self.result = result

    def draw(self, layer=1000):
        self.spr.set_layer(layer)

    def match(self, sprite):
        if self.spr == sprite:
            return True
        return False

    def move(self, dx, dy):
        self.spr.move((dx, dy))

    def move_relative(self, dx, dy):
        self.spr.move_relative((dx, dy))

    def hide(self):
        self.spr.hide()
Beispiel #2
0
class Slide(Stator):
    """ Create a sprite for a slide """
    def __init__(self, sprites, path, name, x, y, w, h, svg_engine=None,
                 function=None):
        if svg_engine is None:
            self.spr = Sprite(sprites, x, y, file_to_pixbuf(path, name, w, h))
        else:
            self.spr = Sprite(sprites, x, y,
                              svg_str_to_pixbuf(svg_engine().svg))
        self.tab_dx = [0, SWIDTH - TABWIDTH]
        self.tab_dy = [2 * SHEIGHT, 2 * SHEIGHT]
        self.tabs = []
        self.tabs.append(Tab(sprites, path, 'tab', x + self.tab_dx[0],
                             y + self.tab_dy[0], TABWIDTH, SHEIGHT))
        self.tabs.append(Tab(sprites, path, 'tab', x + self.tab_dx[1],
                             y + self.tab_dy[1], TABWIDTH, SHEIGHT))
        self.calculate = function
        self.name = name

    def add_textview(self, textview, i=0):
        self.tabs[i].textview = textview
        self.tabs[i].textbuffer = textview.get_buffer()

    def set_fixed(self, fixed):
        for tab in self.tabs:
            tab.fixed = fixed

    def match(self, sprite):
        if sprite == self.spr or sprite == self.tabs[0].spr or \
                sprite == self.tabs[1].spr:
            return True
        return False

    def draw(self, layer=1000):
        self.spr.set_layer(layer)
        self.spr.draw()
        for tab in self.tabs:
            tab.draw()

    def move(self, dx, dy):
        self.spr.move((dx, dy))
        for i, tab in enumerate(self.tabs):
            tab.move(dx + self.tab_dx[i], dy + self.tab_dy[i])

    def move_relative(self, dx, dy):
        self.spr.move_relative((dx, dy))
        for i, tab in enumerate(self.tabs):
            tab.move_relative(dx, dy)

    def hide(self):
        self.spr.hide()
        for tab in self.tabs:
            tab.hide()

    def label(self, label, i=0):
        self.tabs[i].label(label)
Beispiel #3
0
class Card:

    ''' Individual cards '''

    def __init__(self, scale=1.0):
        ''' Create the card and store its attributes '''
        self.spr = None
        self.index = None  # Calculated index
        self._scale = scale

    def create(self, string, attributes=None, sprites=None, file_path=None):
        if attributes is None:
            if self.spr is None:
                self.spr = Sprite(sprites, 0, 0, svg_str_to_pixbuf(string))
            else:
                self.spr.set_image(svg_str_to_pixbuf(string))
            self.index = None
        else:
            self.shape = attributes[0]
            self.color = attributes[1]
            self.num = attributes[2]
            self.fill = attributes[3]
            self.index = self.shape * COLORS * NUMBER * FILLS + \
                self.color * NUMBER * FILLS + \
                self.num * FILLS + \
                self.fill
            if self.spr is None:
                self.spr = Sprite(sprites, 0, 0, svg_str_to_pixbuf(string))
            else:
                self.spr.set_image(svg_str_to_pixbuf(string, True))

            if file_path is not None:
                self.spr.set_image(load_image(file_path, self._scale), i=1,
                                   dx=int(self._scale * CARD_WIDTH * .125),
                                   dy=int(self._scale * CARD_HEIGHT * .125))
        self.spr.set_label_attributes(self._scale * 24)
        self.spr.set_label('')

    def show_card(self, layer=2000):
        ''' Show the card '''
        if self.spr is not None:
            self.spr.set_layer(layer)
            self.spr.draw()

    def hide_card(self):
        ''' Hide a card '''
        if self.spr is not None:
            self.spr.hide()
Beispiel #4
0
class Card:

    ''' Individual cards '''

    def __init__(self, scale=1.0):
        ''' Create the card and store its attributes '''
        self.spr = None
        self.index = None  # Calculated index
        self._scale = scale

    def create(self, string, attributes=None, sprites=None, file_path=None):
        if attributes is None:
            if self.spr is None:
                self.spr = Sprite(sprites, 0, 0, svg_str_to_pixbuf(string))
            else:
                self.spr.set_image(svg_str_to_pixbuf(string))
            self.index = None
        else:
            self.shape = attributes[0]
            self.color = attributes[1]
            self.num = attributes[2]
            self.fill = attributes[3]
            self.index = self.shape * COLORS * NUMBER * FILLS + \
                self.color * NUMBER * FILLS + \
                self.num * FILLS + \
                self.fill
            if self.spr is None:
                self.spr = Sprite(sprites, 0, 0, svg_str_to_pixbuf(string))
            else:
                self.spr.set_image(svg_str_to_pixbuf(string))

            if file_path is not None:
                self.spr.set_image(load_image(file_path, self._scale), i=1,
                                   dx=int(self._scale * CARD_WIDTH * .125),
                                   dy=int(self._scale * CARD_HEIGHT * .125))
        self.spr.set_label_attributes(self._scale * 24)
        self.spr.set_label('')

    def show_card(self, layer=2000):
        ''' Show the card '''
        if self.spr is not None:
            self.spr.set_layer(layer)
            self.spr.draw()

    def hide_card(self):
        ''' Hide a card '''
        if self.spr is not None:
            self.spr.hide()
Beispiel #5
0
class Tab():
    """ Create tabs for the slide; include a TextView for OSK input """
    def __init__(self, sprites, path, name, x, y, w, h):
        self.spr = Sprite(sprites, x, y, file_to_pixbuf(path, name, w, h))
        self.spr.label = "1.0"
        self.spr.type = name
        self.name = name
        self.width = w
        self.textview = None
        self.textbuffer = None
        self.fixed = None
        self.textview_y_offset = 0

    def label(self, label):
        if self.textbuffer is not None:
            self.textbuffer.set_text(label)

    def _move_textview(self, x, y):
        y += self.textview_y_offset
        if self.textview is not None:
            if x > 0 and x < Gdk.Screen.width() - self.width and y > 0:
                self.fixed.move(self.textview, x, y)
                self.textview.show()
            else:
                self.textview.hide()

    def move(self, x, y):
        self.spr.move((x, y))
        self._move_textview(x, y)

    def move_relative(self, dx, dy):
        self.spr.move_relative((dx, dy))
        x, y = self.spr.get_xy()
        self._move_textview(x, y)

    def draw(self, layer=100):
        self.spr.set_layer(layer)
        self.spr.draw()
        x, y = self.spr.get_xy()
        self._move_textview(x, y)

    def hide(self):
        self.spr.hide()
Beispiel #6
0
class Tab():
    """ Create tabs for the slide; include a TextView for OSK input """
    def __init__(self, sprites, path, name, x, y, w, h):
        self.spr = Sprite(sprites, x, y, file_to_pixbuf(path, name, w, h))
        self.spr.label = "1.0"
        self.spr.type = name
        self.name = name
        self.width = w
        self.textview = None
        self.textbuffer = None
        self.fixed = None
        self.textview_y_offset = 0

    def label(self, label):
        if self.textbuffer is not None:
            self.textbuffer.set_text(label)

    def _move_textview(self, x, y):
        y += self.textview_y_offset
        if self.textview is not None:
            if x > 0 and x < Gdk.Screen.width() - self.width and y > 0:
                self.fixed.move(self.textview, x, y)
                self.textview.show()
            else:
                self.textview.hide()

    def move(self, x, y):
        self.spr.move((x, y))
        self._move_textview(x, y)

    def move_relative(self, dx, dy):
        self.spr.move_relative((dx, dy))
        x, y = self.spr.get_xy()
        self._move_textview(x, y)

    def draw(self, layer=100):
        self.spr.set_layer(layer)
        self.spr.draw()
        x, y = self.spr.get_xy()
        self._move_textview(x, y)

    def hide(self):
        self.spr.hide()
Beispiel #7
0
class Stator():
    """ Create a sprite for a stator """
    def __init__(self,
                 sprites,
                 path,
                 name,
                 x,
                 y,
                 w,
                 h,
                 svg_engine=None,
                 calculate=None,
                 result=None):
        if svg_engine is None:
            self.spr = Sprite(sprites, x, y, file_to_pixbuf(path, name, w, h))
        else:
            self.spr = Sprite(sprites, x, y,
                              svg_str_to_pixbuf(svg_engine().svg))
        self.spr.type = name
        self.name = name
        self.calculate = calculate
        self.result = result

    def draw(self, layer=1000):
        self.spr.set_layer(layer)

    def match(self, sprite):
        if self.spr == sprite:
            return True
        return False

    def move(self, dx, dy):
        self.spr.move((dx, dy))

    def move_relative(self, dx, dy):
        self.spr.move_relative((dx, dy))

    def hide(self):
        self.spr.hide()
Beispiel #8
0
class Selector():

    ''' Selector class abstraction  '''

    def __init__(self, turtle_window, n):
        '''This class handles the display of palette selectors (Only relevant
        to GNOME version and very old versions of Sugar).
        '''

        self.shapes = []
        self.spr = None
        self._turtle_window = turtle_window
        self._index = n

        if not n < len(palette_names):
            # Shouldn't happen, but hey...
            debug_output('palette index %d is out of range' % n,
                         self._turtle_window.running_sugar)
            self._name = 'extras'
        else:
            self._name = palette_names[n]

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%soff.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%soff.svg' % (self._name))
                break

        if icon_pathname is not None:
            off_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            off_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrasoff.svg')))
            error_output('Unable to open %soff.svg' % (self._name),
                         self._turtle_window.running_sugar)

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%son.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%son.svg' % (self._name))
                break

        if icon_pathname is not None:
            on_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            on_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrason.svg')))
            error_output('Unable to open %son.svg' % (self._name),
                         self._turtle_window.running_sugar)

        self.shapes.append(off_shape)
        self.shapes.append(on_shape)

        x = int(ICON_SIZE * self._index)
        self.spr = Sprite(self._turtle_window.sprite_list, x, 0, off_shape)
        self.spr.type = 'selector'
        self.spr.name = self._name
        self.set_layer()

    def set_shape(self, i):
        if self.spr is not None and i in [0, 1]:
            self.spr.set_shape(self.shapes[i])

    def set_layer(self, layer=TAB_LAYER):
        if self.spr is not None:
            self.spr.set_layer(layer)

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
Beispiel #9
0
class Game():

    def __init__(self, canvas, parent=None, path=None):
        self._canvas = canvas
        self._parent = parent
        self._parent.show_all()
        self._path = path

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height()
        self._scale = self._width / 1200.
        self._target = 0
        self._tries = 0

        self.level = 0

        self._picture_cards = []
        self._small_picture_cards = []
        self.food_cards = []
        self._group_cards = []
        self._quantity_cards = []
        self._balance_cards = []
        self._last_twenty = []
        self._background = None

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._background = Sprite(
            self._sprites, 0, 0, GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images','background.png'),
                self._width, self._height))
        self._background.set_layer(0)
        self._background.type = None
        self._background.hide()

        self.pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(self._path, 'images', 'word-box.png'),
            int(350 * self._scale), int(100 * self._scale))

        for i in range(len(FOOD_DATA) / 4):
            FOOD.append([FOOD_DATA[i * 4 + NAME], FOOD_DATA[i * 4 + CALS],
                         FOOD_DATA[i * 4 + GROUP], FOOD_DATA[i * 4 + IMAGE]])
            self.food_cards.append(None)
            self._picture_cards.append(None)
            for j in range(6):
                self._small_picture_cards.append(None)
        self.allocate_food(0)

        x = 10
        dx, dy = self.food_cards[0].get_dimensions()

        y = 10
        for i in range(len(MYPLATE)):
            self.word_card_append(self._group_cards, self.pixbuf)
            self._group_cards[-1].type = i
            self._group_cards[-1].set_label(MYPLATE[i][0])
            self._group_cards[-1].move((x, y))
            y += int(dy * 1.25)

        y = 10
        for i in range(len(QUANTITIES)):
            self.word_card_append(self._quantity_cards, self.pixbuf)
            self._quantity_cards[-1].type = i
            self._quantity_cards[-1].set_label(QUANTITIES[i])
            self._quantity_cards[-1].move((x, y))
            y += int(dy * 1.25)

        y = 10
        for i in range(len(BALANCE)):
            self.word_card_append(self._balance_cards, self.pixbuf)
            self._balance_cards[-1].type = i
            self._balance_cards[-1].set_label(BALANCE[i])
            self._balance_cards[-1].move((x, y))
            y += int(dy * 1.25)

        self._smile = Sprite(self._sprites,
                             int(self._width / 4),
                             int(self._height / 4),
                             GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'correct.png'),
                int(self._width / 2),
                int(self._height / 2)))
        self._smile.set_label_attributes(36)
        self._smile.set_margins(10, 0, 10, 0)

        self._frown = Sprite(self._sprites,
                             int(self._width / 4),
                             int(self._height / 4),
                             GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'wrong.png'),
                int(self._width / 2),
                int(self._height / 2)))
        self._frown.set_label_attributes(36)
        self._frown.set_margins(10, 0, 10, 0)

        self.build_food_groups()

        self._all_clear()

    def allocate_food(self, i):
        self.picture_append(os.path.join(self._path, 'images',
                                         FOOD_DATA[i * 4 + IMAGE]), i)
        self.small_picture_append(os.path.join(self._path, 'images',
                                               FOOD_DATA[i * 4 + IMAGE]), i)
        self.word_card_append(self.food_cards, self.pixbuf, i)
        self.food_cards[i].type = i
        self.food_cards[i].set_label(FOOD_DATA[i * 4 + NAME])

    def word_card_append(self, card_list, pixbuf, i=-1):
        if i == -1:
            card_list.append(Sprite(self._sprites, 10, 10, pixbuf))
        else:
            card_list[i] = Sprite(self._sprites, 10, 10, pixbuf)
        card_list[i].set_label_attributes(36)
        card_list[i].set_margins(10, 0, 10, 0)
        card_list[i].hide()

    def picture_append(self, path, i=-1):
        spr = Sprite(
            self._sprites,
            int(self._width / 2.),
            int(self._height / 4.),
            GdkPixbuf.Pixbuf.new_from_file_at_size(
                path, int(self._width / 3.), int(9 * self._width / 12.)))
        if i == -1:
            self._picture_cards.append(spr)
        else:
            self._picture_cards[i] = spr
        self._picture_cards[i].type = 'picture'
        self._picture_cards[i].hide()

    def small_picture_append(self, path, i=-1):
        x = int(self._width / 3.)
        y = int(self._height / 6.)
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path,
            int(self._width / 6.),
            int(3 * self._width / 8.)) 
        for j in range(6):  # up to 6 of each card
            if i == -1:
                self._small_picture_cards.append(Sprite(
                self._sprites, x, y, pixbuf))
                self._small_picture_cards[-1].type = 'picture'
                self._small_picture_cards[-1].hide()
            else:
                self._small_picture_cards[i * 6 + j] = Sprite(
                    self._sprites, x, y, pixbuf)
                self._small_picture_cards[i * 6 + j].type = 'picture'
                self._small_picture_cards[i * 6 + j].hide()
            x += int(self._width / 6.)
            if j == 2:
                x = int(self._width / 3.)
                y += int(3 * self._width / 16.)

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        for p in self._picture_cards:
            if p is not None:
                p.hide()
        for p in self._small_picture_cards:
            if p is not None:
                p.hide()
        for i, w in enumerate(self.food_cards):
            if w is not None:
                w.set_label_color('black')
                w.set_label(FOOD[i][NAME])
                w.hide()
        for i, w in enumerate(self._group_cards):
            w.set_label_color('black')
            w.set_label(MYPLATE[i][0])
            w.hide()
        for i, w in enumerate(self._quantity_cards):
            w.set_label_color('black')
            w.set_label(QUANTITIES[i])
            w.hide()
        for i, w in enumerate(self._balance_cards):
            w.set_label_color('black')
            w.set_label(BALANCE[i])
            w.hide()
        self._smile.hide()
        self._frown.hide()

        self._background.set_layer(1)

    def build_food_groups(self):
        self._my_plate = [[], [], [], []]
        for i, food in enumerate(FOOD):
            self._my_plate[MYPLATE[food[GROUP]][QUANT]].append(i)

    def new_game(self):
        ''' Start a new game. '''
        games = {0: self._name_that_food, 1: self._name_that_food_group,
                 2: self._compare_calories, 3: self._how_much_to_eat,
                 4: self._balanced_meal}
        self._all_clear()
        
        games[self.level]()
        
        self._frown.set_label('')
        self._smile.set_label('')
        self._tries = 0

    def _name_that_food(self):
        ''' Choose food cards and one matching food picture '''
        x = 10
        y = 10
        dx, dy = self.food_cards[0].get_dimensions()

        # Select some cards
        word_list = []
        for i in range(NCARDS):
            j = int(uniform(0, len(FOOD)))
            while j in word_list:
                j = int(uniform(0, len(FOOD)))
            word_list.append(j)

        # Show the word cards from the list
        for i in word_list:
            if self.food_cards[i] is None:
                self.allocate_food(i)
            self.food_cards[i].set_layer(100)
            self.food_cards[i].move((x, y))
            y += int(dy * 1.25)

        # Choose a random food image from the list and show it.
        self._target = self.food_cards[
            word_list[int(uniform(0, NCARDS))]].type
        while self._target in self._last_twenty:
            self._target = self.food_cards[
                word_list[int(uniform(0, NCARDS))]].type
        self._last_twenty.append(self._target)
        if len(self._last_twenty) > 20:
            self._last_twenty.remove(self._last_twenty[0])
            
        self._picture_cards[self._target].set_layer(100)

    def _name_that_food_group(self):
        ''' Show group cards and one food picture '''
        for i in range(len(MYPLATE)):
            self._group_cards[i].set_layer(100)

        # Choose a random food image and show it.
        self._target = int(uniform(0, len(FOOD)))
        if self.food_cards[self._target] is None:
            self.allocate_food(self._target)
        self._picture_cards[self._target].set_layer(100)

    def _compare_calories(self):
        ''' Choose food cards and compare the calories '''
        x = 10
        y = 10
        dx, dy = self.food_cards[0].get_dimensions()

        # Select some cards
        word_list = []
        for i in range(6):
            j = int(uniform(0, len(FOOD)))
            while j in word_list:
                j = int(uniform(0, len(FOOD)))
            word_list.append(j)
            if self.food_cards[j] is None:
                self.allocate_food(j)

        # Show the word cards from the list
        for i in word_list:
            self.food_cards[i].set_layer(100)
            self.food_cards[i].move((x, y))
            y += int(dy * 1.25)

        # Show food images
        self._target = word_list[0]
        for i in range(5):
             if FOOD[word_list[i + 1]][CALS] > FOOD[self._target][CALS]:
                 self._target = word_list[i + 1]
        self._small_picture_cards[word_list[0] * 6].set_layer(100)
        self._small_picture_cards[word_list[1] * 6 + 1].set_layer(100)
        self._small_picture_cards[word_list[2] * 6 + 2].set_layer(100)
        self._small_picture_cards[word_list[3] * 6 + 3].set_layer(100)
        self._small_picture_cards[word_list[4] * 6 + 4].set_layer(100)
        self._small_picture_cards[word_list[5] * 6 + 5].set_layer(100)

    def _how_much_to_eat(self):
        ''' Show quantity cards and one food picture '''
        for i in range(len(QUANTITIES)):
            self._quantity_cards[i].set_layer(100)

        # Choose a random image from the list and show it.
        self._target = int(uniform(0, len(FOOD)))
        if self.food_cards[self._target] is None:
            self.allocate_food(self._target)
        self._picture_cards[self._target].set_layer(100)

    def _balanced_meal(self):
        ''' A well-balanced meal '''
        for i in range(2):
            self._balance_cards[i].set_layer(100)

        # Determine how many foods from each group
        n = [0, 0, 0, 0]
        n[0] = int(uniform(0, 2.5))
        n[1] = int(uniform(0, 3 - n[0]))
        n[2] = 3 - n[0] - n[1]
        n[3] = 6 - n[0] - n[1] - n[2]

        # Fill a plate with foods from different groups
        meal = []
        for i in range(n[0]):  # Sweets
            j = int(uniform(0, len(self._my_plate[0])))
            meal.append(self._my_plate[0][j])
        for i in range(n[1]):  # Dairy
            j = int(uniform(0, len(self._my_plate[1])))
            meal.append(self._my_plate[1][j])
        for i in range(n[2]):  # Protein and Fruits
            j = int(uniform(0, len(self._my_plate[2])))
            meal.append(self._my_plate[2][j])
        for i in range(n[3]):  # Veggies and Grains
            j = int(uniform(0, len(self._my_plate[3])))
            meal.append(self._my_plate[3][j])

        if n[0] < 2 and n[1] < 2 and n[2] < n[3]:
            self._target = 0  # Balanced meal
        else:
            self._target = 1

        for i in range(6):
            if self.food_cards[meal[i]] is None:
                self.allocate_food(meal[i])
        # Randomly position small cards
        self._small_picture_cards[meal[3] * 6].set_layer(100)
        self._small_picture_cards[meal[4] * 6 + 1].set_layer(100)
        self._small_picture_cards[meal[1] * 6 + 2].set_layer(100)
        self._small_picture_cards[meal[2] * 6 + 3].set_layer(100)
        self._small_picture_cards[meal[5] * 6 + 4].set_layer(100)
        self._small_picture_cards[meal[0] * 6 + 5].set_layer(100)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = map(int, event.get_coords())
        spr = self._sprites.find_sprite((x, y))
        if spr == None:
            return
        # We only care about clicks on word cards
        if type(spr.type) != int:
            return

        # Which card was clicked? Set its label to red.
        spr.set_label_color('red')
        label = spr.labels[0]
        spr.set_label(label)

        if self.level == 0:
            if spr.type == self._target:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self.food_cards[self._target].set_label_color('blue')
                label = self.food_cards[self._target].labels[0]
                self.food_cards[self._target].set_label(label)
        elif self.level == 1:
            i = FOOD[self._target][GROUP]
            if spr.type == i:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self._group_cards[i].set_label_color('blue')
                label = self._group_cards[i].labels[0]
                self._group_cards[i].set_label(label)
        elif self.level == 2:
            if spr.type == self._target:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self.food_cards[self._target].set_label_color('blue')
                label = self.food_cards[self._target].labels[0]
                self.food_cards[self._target].set_label(label)
        elif self.level == 3:
            i = MYPLATE[FOOD[self._target][GROUP]][QUANT]
            if spr.type == i:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self._quantity_cards[i].set_label_color('blue')
                label = self._quantity_cards[i].labels[0]
                self._quantity_cards[i].set_label(label)
        elif self.level == 4:
            if self._target == spr.type:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self._balance_cards[self._target].set_label_color('blue')
                label = self._balance_cards[self._target].labels[0]
                self._balance_cards[self._target].set_label(label)
        else:
            _logger.debug('unknown play level %d' % (self.level))

        # Play again
        if self._tries == 3:
            GObject.timeout_add(2000, self.new_game)
        else:
            GObject.timeout_add(1000, self._reset_game)
        return True

    def _reset_game(self):
        self._frown.hide()
        if self.level in [0, 2]:
            for i, w in enumerate(self.food_cards):
                w.set_label_color('black')
                w.set_label(FOOD[i][NAME])
        elif self.level == 1:
            for i, w in enumerate(self._group_cards):
                w.set_label_color('black')
                w.set_label(MYPLATE[i][0])
        elif self.level == 3:
            for i, w in enumerate(self._quantity_cards):
                w.set_label_color('black')
                w.set_label(QUANTITIES[i])
        elif self.level == 4:
            for i, w in enumerate(self._balance_cards):
                w.set_label_color('black')
                w.set_label(BALANCE[i])

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()
class AbacusGeneric():
    """ A generic abacus: a frame, rods, and beads. """

    def __init__(self, abacus):
        """ Specify parameters that define the abacus """
        self.abacus = abacus
        self.set_parameters()
        self.create()

    def set_parameters(self):
        """ Define the physical paramters. """
        self.name = "suanpan"
        self.num_rods = 15
        self.bot_beads = 5
        self.top_beads = 2
        self.base = 10
        self.top_factor = 5

    def create(self):
        """ Create and position the sprites that compose the abacus """

        # Width is a function of the number of rods
        self.frame_width = self.num_rods*(BWIDTH+BOFFSET)+FSTROKE*2

        # Height is a function of the number of beads
        if self.top_beads > 0:
            self.frame_height = (self.bot_beads+self.top_beads+5)*BHEIGHT +\
                                FSTROKE*2
        else:
            self.frame_height = (self.bot_beads+2)*BHEIGHT + FSTROKE*2

        # Draw the frame...
        x = (self.abacus.width-(self.frame_width*self.abacus.scale))/2
        y = (self.abacus.height-(self.frame_height*self.abacus.scale))/2
        _frame = _svg_header(self.frame_width, self.frame_height,
                             self.abacus.scale) +\
                 _svg_rect(self.frame_width, self.frame_height, 
                           FSTROKE/2, FSTROKE/2, 0, 0, "#000000", "#000000") +\
                 _svg_rect(self.frame_width-(FSTROKE*2), 
                           self.frame_height-(FSTROKE*2), 0, 0,
                           FSTROKE, FSTROKE, "#808080", "#000000") +\
                 _svg_footer()
        self.frame = Sprite(self.abacus.sprites, x, y, 
                            _svg_str_to_pixbuf(_frame))
        self.frame.type = 'frame'

        # and then the rods and beads.
        self.rods = []
        self.beads = []
        x += FSTROKE*self.abacus.scale
        y += FSTROKE*self.abacus.scale

        self.draw_rods_and_beads(x, y)

        # Draw the dividing bar...
        _bar = _svg_header(self.frame_width-(FSTROKE*2), BHEIGHT,
                           self.abacus.scale) +\
               _svg_rect(self.frame_width-(FSTROKE*2), BHEIGHT, 0, 0, 0, 0,
                         "#000000", "#000000") +\
               _svg_footer()
        if self.top_beads > 0:
            self.bar = Sprite(self.abacus.sprites, x,
                              y+(self.top_beads+2)*BHEIGHT*self.abacus.scale,
                              _svg_str_to_pixbuf(_bar))
        else:
            self.bar = Sprite(self.abacus.sprites, x,
                              y-FSTROKE*self.abacus.scale,
                              _svg_str_to_pixbuf(_bar))

        self.bar.type = 'frame'
        self.bar.set_label_color('white')

        # and finally, the mark.
        _mark = _svg_header(20, 15, self.abacus.scale) +\
                _svg_indicator() +\
                _svg_footer()
        dx = (BWIDTH+BOFFSET)*self.abacus.scale
        self.mark = Sprite(self.abacus.sprites, x+(self.num_rods-1)*dx,
                           y-((FSTROKE/2)*self.abacus.scale),
                           _svg_str_to_pixbuf(_mark))
        self.mark.type = 'mark'

    def draw_rods_and_beads(self, x, y):
        """ Draw the rods and beads """
        _white = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\
                 _svg_bead("#ffffff", "#000000") +\
                 _svg_footer()
        _yellow1 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\
                 _svg_bead("#ffffcc", "#000000") +\
                 _svg_footer()
        _yellow2 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\
                 _svg_bead("#ffff88", "#000000") +\
                 _svg_footer()
        _yellow3 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\
                 _svg_bead("#ffff00", "#000000") +\
                 _svg_footer()
        self.colors = [_svg_str_to_pixbuf(_white),
                       _svg_str_to_pixbuf(_yellow1),
                       _svg_str_to_pixbuf(_yellow2),
                       _svg_str_to_pixbuf(_yellow3)]

        dx = (BWIDTH+BOFFSET)*self.abacus.scale
        bo =  (BWIDTH-BOFFSET)*self.abacus.scale/4
        ro =  (BWIDTH+5)*self.abacus.scale/2
        for i in range(self.num_rods):
            _rod = _svg_header(10, self.frame_height-(FSTROKE*2),
                               self.abacus.scale) +\
                   _svg_rect(10, self.frame_height-(FSTROKE*2), 0, 0, 0, 0,
                             ROD_COLORS[i%len(ROD_COLORS)], "#404040") +\
                   _svg_footer()
            self.rods.append(Sprite(self.abacus.sprites, x+i*dx+ro, y,
                                    _svg_str_to_pixbuf(_rod)))

            for b in range(self.top_beads):
                self.beads.append(Bead(Sprite(self.abacus.sprites, x+i*dx+bo,
                                              y+b*BHEIGHT*self.abacus.scale,
                                              self.colors[0]),
                                       2*BHEIGHT*self.abacus.scale,
                                       self.top_factor*(pow(self.base,
                                                        self.num_rods-i-1))))
            for b in range(self.bot_beads):
                if self.top_beads > 0:
                    self.beads.append(Bead(Sprite(self.abacus.sprites,
                                                  x+i*dx+bo,
                                                  y+(self.top_beads+5+b)*\
                                                  BHEIGHT*self.abacus.scale,
                                                  self.colors[0]),
                                           2*BHEIGHT*self.abacus.scale,
                                           pow(self.base,self.num_rods-i-1)))
                else:
                    self.beads.append(Bead(Sprite(self.abacus.sprites,
                                                  x+i*dx+bo,
                                                  y+(2+b)*BHEIGHT\
                                                  *self.abacus.scale,
                                                  self.colors[0]),
                                           2*BHEIGHT*self.abacus.scale,
                                           pow(self.base,self.num_rods-i-1)))

        for rod in self.rods:
            rod.type = "frame"

    def hide(self):
        """ Hide the rod, beads, mark, and frame. """
        for rod in self.rods:
            rod.hide()
        for bead in self.beads:
            bead.hide()
        self.bar.hide()
        self.frame.hide()
        self.mark.hide()

    def show(self):
        """ Show the rod, beads, mark, and frame. """
        self.frame.set_layer(FRAME_LAYER)
        for rod in self.rods:
            rod.set_layer(ROD_LAYER)
        for bead in self.beads:
            bead.show()
        self.bar.set_layer(BAR_LAYER)
        self.mark.set_layer(MARK_LAYER)

    def set_value(self, string):
        """ Set abacus to value in string """
        _logger.debug("restoring %s: %s" % (self.name, string))
        # String has two bytes per column.
        v = []
        for r in range(self.num_rods):
            v.append(0)

        # Convert string to column values.
        if len(string) == 2*self.num_rods:
            for i in range(self.num_rods):
                v[self.num_rods-i-1] = int(
                              string[2*self.num_rods-i*2-1:2*self.num_rods-i*2])
        else:
            _logger.debug("bad saved string %s (%d != 2*%d)" % (string,
                          len(string), self.num_rods))

        # Move the beads to correspond to column values.
        for r in range(self.num_rods):
            self.set_rod_value(r, v[r])

    def set_rod_value(self, r, v):
        """ Move beads on rod r to represent value v """
        bot = v % self.top_factor
        top = (v-bot)/self.top_factor
        top_bead_index = r*(self.top_beads+self.bot_beads)
        bot_bead_index = r*(self.top_beads+self.bot_beads)+self.top_beads

        # Clear the top.
        for i in range(self.top_beads):
            if self.beads[top_bead_index+i].get_state() == 1:
                self.beads[top_bead_index+i].move_up()
        # Clear the bottom.
        for i in range(self.bot_beads):
            if self.beads[bot_bead_index+i].get_state() == 1:
                self.beads[bot_bead_index+i].move_down()
        # Set the top.
        for i in range(top):
            self.beads[top_bead_index+self.top_beads-i-1].move_down()
        # Set the bottom
        for i in range(bot):
            self.beads[bot_bead_index+i].move_up()

    def value(self, count_beads=False):
        """ Return a string representing the value of each rod. """
        string = ''
        v = []
        for r in range(self.num_rods+1): # +1 for overflow
            v.append(0)

        # Tally the values on each rod.
        for i, bead in enumerate(self.beads):
            r = i/(self.top_beads+self.bot_beads)
            j = i % (self.top_beads+self.bot_beads)
            if bead.get_state() == 1:
                if j < self.top_beads:
                    v[r+1] += self.top_factor
                else:
                    v[r+1] += 1

        if count_beads:
            # Save the value associated with each rod as a 2-byte integer.
            for j in v[1:]:
                string += "%2d" % (j)
        else:
            sum = 0
            for bead in self.beads:
                sum += bead.get_value()
            string = str(sum)

        return(string)

    def label(self, string):
        """ Label the crossbar with the string. (Used with self.value) """
        self.bar.set_label(string)

    def move_mark(self, dx):
        """ Move indicator horizontally across the top of the frame. """
        self.mark.move_relative((dx, 0))

    def fade_colors(self):
        """ Reduce the saturation level of every bead. """
        for bead in self.beads:
            if bead.get_level() > 0:
                bead.set_color(self.colors[bead.get_level()-1])
                bead.set_level(bead.get_level()-1)

    def move_bead(self, sprite, dy):
        """ Move a bead (or beads) up or down a rod. """

        # find the bead associated with the sprite
        i = -1
        for bead in self.beads:
            if sprite == bead.spr:
                i = self.beads.index(bead)
                break
        if i == -1:
            print "bead not found"
            return

        b = i % (self.top_beads+self.bot_beads)
        if b < self.top_beads:
            if dy > 0 and bead.get_state() == 0:
                self.fade_colors()
                bead.set_color(self.colors[3])
                bead.move_down()
                # Make sure beads below this bead are also moved.
                for ii in range(self.top_beads-b):
                    if self.beads[i+ii].state == 0:
                        self.beads[i+ii].set_color(self.colors[3])
                        self.beads[i+ii].move_down()
            elif dy < 0 and bead.state == 1:
                self.fade_colors()
                bead.set_color(self.colors[3])
                bead.move_up()
                # Make sure beads above this bead are also moved.
                for ii in range(b+1):
                    if self.beads[i-ii].state == 1:
                        self.beads[i-ii].set_color(self.colors[3])
                        self.beads[i-ii].move_up()
        else:
            if dy < 0 and bead.state == 0:
                self.fade_colors()
                bead.set_color(self.colors[3])
                bead.move_up()
                # Make sure beads above this bead are also moved.
                for ii in range(b-self.top_beads+1):
                    if self.beads[i-ii].state == 0:
                        self.beads[i-ii].set_color(self.colors[3])
                        self.beads[i-ii].move_up()
            elif dy > 0 and bead.state == 1:
                self.fade_colors()
                bead.set_color(self.colors[3])
                bead.move_down()
                # Make sure beads below this bead are also moved.
                for ii in range(self.top_beads+self.bot_beads-b):
                    if self.beads[i+ii].state == 1:
                        self.beads[i+ii].set_color(self.colors[3])
                        self.beads[i+ii].move_down()
Beispiel #11
0
class Game():
    def __init__(self, canvas, parent=None, path=None):
        self._canvas = canvas
        self._parent = parent
        self._parent.show_all()
        self._path = path

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height()
        self._scale = self._width / 1200.
        self._target = 0
        self._tries = 0

        self.level = 0

        self._picture_cards = []
        self._small_picture_cards = []
        self.food_cards = []
        self._group_cards = []
        self._quantity_cards = []
        self._balance_cards = []
        self._last_twenty = []
        self._background = None

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._background = Sprite(
            self._sprites, 0, 0,
            GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'background.png'),
                self._width, self._height))
        self._background.set_layer(0)
        self._background.type = None
        self._background.hide()

        self.pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(self._path, 'images', 'word-box.png'),
            int(350 * self._scale), int(100 * self._scale))

        for i in range(len(FOOD_DATA) / 4):
            FOOD.append([
                FOOD_DATA[i * 4 + NAME], FOOD_DATA[i * 4 + CALS],
                FOOD_DATA[i * 4 + GROUP], FOOD_DATA[i * 4 + IMAGE]
            ])
            self.food_cards.append(None)
            self._picture_cards.append(None)
            for j in range(6):
                self._small_picture_cards.append(None)
        self.allocate_food(0)

        x = 10
        dx, dy = self.food_cards[0].get_dimensions()

        y = 10
        for i in range(len(MYPLATE)):
            self.word_card_append(self._group_cards, self.pixbuf)
            self._group_cards[-1].type = i
            self._group_cards[-1].set_label(MYPLATE[i][0])
            self._group_cards[-1].move((x, y))
            y += int(dy * 1.25)

        y = 10
        for i in range(len(QUANTITIES)):
            self.word_card_append(self._quantity_cards, self.pixbuf)
            self._quantity_cards[-1].type = i
            self._quantity_cards[-1].set_label(QUANTITIES[i])
            self._quantity_cards[-1].move((x, y))
            y += int(dy * 1.25)

        y = 10
        for i in range(len(BALANCE)):
            self.word_card_append(self._balance_cards, self.pixbuf)
            self._balance_cards[-1].type = i
            self._balance_cards[-1].set_label(BALANCE[i])
            self._balance_cards[-1].move((x, y))
            y += int(dy * 1.25)

        self._smile = Sprite(
            self._sprites, int(self._width / 4), int(self._height / 4),
            GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'correct.png'),
                int(self._width / 2), int(self._height / 2)))
        self._smile.set_label_attributes(36)
        self._smile.set_margins(10, 0, 10, 0)

        self._frown = Sprite(
            self._sprites, int(self._width / 4), int(self._height / 4),
            GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'wrong.png'),
                int(self._width / 2), int(self._height / 2)))
        self._frown.set_label_attributes(36)
        self._frown.set_margins(10, 0, 10, 0)

        self.build_food_groups()

        self._all_clear()

    def allocate_food(self, i):
        self.picture_append(
            os.path.join(self._path, 'images', FOOD_DATA[i * 4 + IMAGE]), i)
        self.small_picture_append(
            os.path.join(self._path, 'images', FOOD_DATA[i * 4 + IMAGE]), i)
        self.word_card_append(self.food_cards, self.pixbuf, i)
        self.food_cards[i].type = i
        self.food_cards[i].set_label(FOOD_DATA[i * 4 + NAME])

    def word_card_append(self, card_list, pixbuf, i=-1):
        if i == -1:
            card_list.append(Sprite(self._sprites, 10, 10, pixbuf))
        else:
            card_list[i] = Sprite(self._sprites, 10, 10, pixbuf)
        card_list[i].set_label_attributes(36)
        card_list[i].set_margins(10, 0, 10, 0)
        card_list[i].hide()

    def picture_append(self, path, i=-1):
        spr = Sprite(
            self._sprites, int(self._width / 2.), int(self._height / 4.),
            GdkPixbuf.Pixbuf.new_from_file_at_size(path, int(self._width / 3.),
                                                   int(9 * self._width / 12.)))
        if i == -1:
            self._picture_cards.append(spr)
        else:
            self._picture_cards[i] = spr
        self._picture_cards[i].type = 'picture'
        self._picture_cards[i].hide()

    def small_picture_append(self, path, i=-1):
        x = int(self._width / 3.)
        y = int(self._height / 6.)
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path, int(self._width / 6.), int(3 * self._width / 8.))
        for j in range(6):  # up to 6 of each card
            if i == -1:
                self._small_picture_cards.append(
                    Sprite(self._sprites, x, y, pixbuf))
                self._small_picture_cards[-1].type = 'picture'
                self._small_picture_cards[-1].hide()
            else:
                self._small_picture_cards[i * 6 + j] = Sprite(
                    self._sprites, x, y, pixbuf)
                self._small_picture_cards[i * 6 + j].type = 'picture'
                self._small_picture_cards[i * 6 + j].hide()
            x += int(self._width / 6.)
            if j == 2:
                x = int(self._width / 3.)
                y += int(3 * self._width / 16.)

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        for p in self._picture_cards:
            if p is not None:
                p.hide()
        for p in self._small_picture_cards:
            if p is not None:
                p.hide()
        for i, w in enumerate(self.food_cards):
            if w is not None:
                w.set_label_color('black')
                w.set_label(FOOD[i][NAME])
                w.hide()
        for i, w in enumerate(self._group_cards):
            w.set_label_color('black')
            w.set_label(MYPLATE[i][0])
            w.hide()
        for i, w in enumerate(self._quantity_cards):
            w.set_label_color('black')
            w.set_label(QUANTITIES[i])
            w.hide()
        for i, w in enumerate(self._balance_cards):
            w.set_label_color('black')
            w.set_label(BALANCE[i])
            w.hide()
        self._smile.hide()
        self._frown.hide()

        self._background.set_layer(1)

    def build_food_groups(self):
        self._my_plate = [[], [], [], []]
        for i, food in enumerate(FOOD):
            self._my_plate[MYPLATE[food[GROUP]][QUANT]].append(i)

    def new_game(self):
        ''' Start a new game. '''
        games = {
            0: self._name_that_food,
            1: self._name_that_food_group,
            2: self._compare_calories,
            3: self._how_much_to_eat,
            4: self._balanced_meal
        }
        self._all_clear()

        games[self.level]()

        self._frown.set_label('')
        self._smile.set_label('')
        self._tries = 0

    def _name_that_food(self):
        ''' Choose food cards and one matching food picture '''
        x = 10
        y = 10
        dx, dy = self.food_cards[0].get_dimensions()

        # Select some cards
        word_list = []
        for i in range(NCARDS):
            j = int(uniform(0, len(FOOD)))
            while j in word_list:
                j = int(uniform(0, len(FOOD)))
            word_list.append(j)

        # Show the word cards from the list
        for i in word_list:
            if self.food_cards[i] is None:
                self.allocate_food(i)
            self.food_cards[i].set_layer(100)
            self.food_cards[i].move((x, y))
            y += int(dy * 1.25)

        # Choose a random food image from the list and show it.
        self._target = self.food_cards[word_list[int(uniform(0, NCARDS))]].type
        while self._target in self._last_twenty:
            self._target = self.food_cards[word_list[int(uniform(
                0, NCARDS))]].type
        self._last_twenty.append(self._target)
        if len(self._last_twenty) > 20:
            self._last_twenty.remove(self._last_twenty[0])

        self._picture_cards[self._target].set_layer(100)

    def _name_that_food_group(self):
        ''' Show group cards and one food picture '''
        for i in range(len(MYPLATE)):
            self._group_cards[i].set_layer(100)

        # Choose a random food image and show it.
        self._target = int(uniform(0, len(FOOD)))
        if self.food_cards[self._target] is None:
            self.allocate_food(self._target)
        self._picture_cards[self._target].set_layer(100)

    def _compare_calories(self):
        ''' Choose food cards and compare the calories '''
        x = 10
        y = 10
        dx, dy = self.food_cards[0].get_dimensions()

        # Select some cards
        word_list = []
        for i in range(6):
            j = int(uniform(0, len(FOOD)))
            while j in word_list:
                j = int(uniform(0, len(FOOD)))
            word_list.append(j)
            if self.food_cards[j] is None:
                self.allocate_food(j)

        # Show the word cards from the list
        for i in word_list:
            self.food_cards[i].set_layer(100)
            self.food_cards[i].move((x, y))
            y += int(dy * 1.25)

        # Show food images
        self._target = word_list[0]
        for i in range(5):
            if FOOD[word_list[i + 1]][CALS] > FOOD[self._target][CALS]:
                self._target = word_list[i + 1]
        self._small_picture_cards[word_list[0] * 6].set_layer(100)
        self._small_picture_cards[word_list[1] * 6 + 1].set_layer(100)
        self._small_picture_cards[word_list[2] * 6 + 2].set_layer(100)
        self._small_picture_cards[word_list[3] * 6 + 3].set_layer(100)
        self._small_picture_cards[word_list[4] * 6 + 4].set_layer(100)
        self._small_picture_cards[word_list[5] * 6 + 5].set_layer(100)

    def _how_much_to_eat(self):
        ''' Show quantity cards and one food picture '''
        for i in range(len(QUANTITIES)):
            self._quantity_cards[i].set_layer(100)

        # Choose a random image from the list and show it.
        self._target = int(uniform(0, len(FOOD)))
        if self.food_cards[self._target] is None:
            self.allocate_food(self._target)
        self._picture_cards[self._target].set_layer(100)

    def _balanced_meal(self):
        ''' A well-balanced meal '''
        for i in range(2):
            self._balance_cards[i].set_layer(100)

        # Determine how many foods from each group
        n = [0, 0, 0, 0]
        n[0] = int(uniform(0, 2.5))
        n[1] = int(uniform(0, 3 - n[0]))
        n[2] = 3 - n[0] - n[1]
        n[3] = 6 - n[0] - n[1] - n[2]

        # Fill a plate with foods from different groups
        meal = []
        for i in range(n[0]):  # Sweets
            j = int(uniform(0, len(self._my_plate[0])))
            meal.append(self._my_plate[0][j])
        for i in range(n[1]):  # Dairy
            j = int(uniform(0, len(self._my_plate[1])))
            meal.append(self._my_plate[1][j])
        for i in range(n[2]):  # Protein and Fruits
            j = int(uniform(0, len(self._my_plate[2])))
            meal.append(self._my_plate[2][j])
        for i in range(n[3]):  # Veggies and Grains
            j = int(uniform(0, len(self._my_plate[3])))
            meal.append(self._my_plate[3][j])

        if n[0] < 2 and n[1] < 2 and n[2] < n[3]:
            self._target = 0  # Balanced meal
        else:
            self._target = 1

        for i in range(6):
            if self.food_cards[meal[i]] is None:
                self.allocate_food(meal[i])
        # Randomly position small cards
        self._small_picture_cards[meal[3] * 6].set_layer(100)
        self._small_picture_cards[meal[4] * 6 + 1].set_layer(100)
        self._small_picture_cards[meal[1] * 6 + 2].set_layer(100)
        self._small_picture_cards[meal[2] * 6 + 3].set_layer(100)
        self._small_picture_cards[meal[5] * 6 + 4].set_layer(100)
        self._small_picture_cards[meal[0] * 6 + 5].set_layer(100)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = list(map(int, event.get_coords()))
        spr = self._sprites.find_sprite((x, y))
        if spr == None:
            return
        # We only care about clicks on word cards
        if type(spr.type) != int:
            return

        # Which card was clicked? Set its label to red.
        spr.set_label_color('red')
        label = spr.labels[0]
        spr.set_label(label)

        if self.level == 0:
            if spr.type == self._target:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self.food_cards[self._target].set_label_color('blue')
                label = self.food_cards[self._target].labels[0]
                self.food_cards[self._target].set_label(label)
        elif self.level == 1:
            i = FOOD[self._target][GROUP]
            if spr.type == i:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self._group_cards[i].set_label_color('blue')
                label = self._group_cards[i].labels[0]
                self._group_cards[i].set_label(label)
        elif self.level == 2:
            if spr.type == self._target:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self.food_cards[self._target].set_label_color('blue')
                label = self.food_cards[self._target].labels[0]
                self.food_cards[self._target].set_label(label)
        elif self.level == 3:
            i = MYPLATE[FOOD[self._target][GROUP]][QUANT]
            if spr.type == i:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self._quantity_cards[i].set_label_color('blue')
                label = self._quantity_cards[i].labels[0]
                self._quantity_cards[i].set_label(label)
        elif self.level == 4:
            if self._target == spr.type:
                self._smile.set_layer(200)
                self._tries = 3
            else:
                self._frown.set_layer(200)
                self._tries += 1
            if self._tries == 3:
                self._balance_cards[self._target].set_label_color('blue')
                label = self._balance_cards[self._target].labels[0]
                self._balance_cards[self._target].set_label(label)
        else:
            _logger.debug('unknown play level %d' % (self.level))

        # Play again
        if self._tries == 3:
            GObject.timeout_add(2000, self.new_game)
        else:
            GObject.timeout_add(1000, self._reset_game)
        return True

    def _reset_game(self):
        self._frown.hide()
        if self.level in [0, 2]:
            for i, w in enumerate(self.food_cards):
                w.set_label_color('black')
                w.set_label(FOOD[i][NAME])
        elif self.level == 1:
            for i, w in enumerate(self._group_cards):
                w.set_label_color('black')
                w.set_label(MYPLATE[i][0])
        elif self.level == 3:
            for i, w in enumerate(self._quantity_cards):
                w.set_label_color('black')
                w.set_label(QUANTITIES[i])
        elif self.level == 4:
            for i, w in enumerate(self._balance_cards):
                w.set_label_color('black')
                w.set_label(BALANCE[i])

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y, event.area.width,
                     event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()
Beispiel #12
0
class Game():
    def __init__(self, canvas, parent=None, colors=['#A0FFA0', '#FF8080']):
        self._activity = parent
        self._colors = colors

        self._canvas = canvas
        parent.show_all()

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - (GRID_CELL_SIZE * 1.5)
        self._scale = self._height / (14.0 * DOT_SIZE * 1.2)
        self._scale_gameover = self._height / (4.0 * DOT_SIZE_GAMEOVER * 1.2)
        self._dot_size = int(DOT_SIZE * self._scale)
        self._dot_size_gameover = int(DOT_SIZE_GAMEOVER * self._scale)
        self._turtle_offset = 0
        self._space = int(self._dot_size / 5.)
        self._space_gameover = int(self._dot_size_gameover / 5.)
        self._orientation = 0
        self.level = 0
        self.custom_strategy = None
        self.strategies = [
            BEGINNER_STRATEGY, INTERMEDIATE_STRATEGY, EXPERT_STRATEGY,
            self.custom_strategy
        ]
        self.strategy = self.strategies[self.level]
        self._timeout_id = None
        self.best_time = self.load_best_time()
        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._dots = []
        self._gameover = []
        self._your_time = []
        self._best_time = []
        self._win_lose = []
        for y in range(THIRTEEN):
            for x in range(THIRTEEN):
                offset_x = int((self._width - THIRTEEN * (self._dot_size + \
                                      self._space) - self._space) / 2.)
                if y % 2 == 1:
                    offset_x += int((self._dot_size + self._space) / 2.)
                if x == 0 or y == 0 or x == THIRTEEN - 1 or y == THIRTEEN - 1:
                    self._dots.append(
                        Sprite(self._sprites,
                               offset_x + x * (self._dot_size + self._space),
                               y * (self._dot_size + self._space),
                               self._new_dot('#B0B0B0', self._dot_size)))
                else:
                    self._dots.append(
                        Sprite(
                            self._sprites,
                            offset_x + x * (self._dot_size + self._space),
                            y * (self._dot_size + self._space),
                            self._new_dot(self._colors[FILL], self._dot_size)))
                    self._dots[-1].type = False  # not set

        # Put a turtle at the center of the screen...
        self._turtle_images = []
        self._rotate_turtle(self._new_turtle())
        self._turtle = Sprite(self._sprites, 0, 0, self._turtle_images[0])
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())

        # ...and initialize.
        self._all_clear()

    def _move_turtle(self, pos):
        ''' Move turtle and add its offset '''
        self._turtle.move(pos)
        self._turtle.move_relative(
            (-self._turtle_offset, -self._turtle_offset))

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        # Clear dots
        for gameover_shape in self._gameover:
            gameover_shape.hide()
        for win_lose_shape in self._win_lose:
            win_lose_shape.hide()
        for your_time_shape in self._your_time:
            your_time_shape.hide()
        for highscore_shape in self._best_time:
            highscore_shape.hide()
        for dot in self._dots:
            if dot.type:
                dot.type = False
                dot.set_shape(self._new_dot(self._colors[FILL],
                                            self._dot_size))
            dot.set_label('')
            dot.set_layer(100)
        self._turtle.set_layer(100)
        # Recenter the turtle
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())
        self._turtle.set_shape(self._turtle_images[0])
        self._set_label('')
        if self._timeout_id is not None:
            GLib.source_remove(self._timeout_id)
            self._timeout_id = None

    def new_game(self, saved_state=None):
        ''' Start a new game. '''
        self.gameover_flag = False
        self.game_lost = False
        self._all_clear()
        # Fill in a few dots to start
        for i in range(15):
            n = int(uniform(0, THIRTEEN * THIRTEEN))
            if self._dots[n].type is not None:
                self._dots[n].type = True
                self._dots[n].set_shape(
                    self._new_dot(self._colors[STROKE], self._dot_size))
        # Calculate the distances to the edge
        self._initialize_weights()
        self.game_start_time = time.time()
        self.strategy = self.strategies[self.level]
        self._timeout_id = None

    def _set_label(self, string):
        ''' Set the label in the toolbar or the window frame. '''
        self._activity.status.set_label(string)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = list(map(int, event.get_coords()))

        spr = self._sprites.find_sprite((x, y), inverse=True)
        if spr == None:
            return

        if spr.type is not None and not spr.type:
            spr.type = True
            spr.set_shape(self._new_dot(self._colors[STROKE], self._dot_size))
            self._weights[self._dots.index(spr)] = 1000
            self._test_game_over(self._move_the_turtle())
        return True

    def _find_the_turtle(self):
        turtle_pos = self._turtle.get_xy()
        turtle_dot = None
        for dot in self._dots:
            pos = dot.get_xy()
            # Turtle is offset
            if pos[0] == turtle_pos[0] + self._turtle_offset and \
               pos[1] == turtle_pos[1] + self._turtle_offset:
                turtle_dot = self._dots.index(dot)
                break
        if turtle_dot is None:
            _logger.debug('Cannot find the turtle...')
            return None
        return turtle_dot

    def _move_the_turtle(self):
        ''' Move the turtle after each click '''
        self._turtle_dot = self._find_the_turtle()
        if self._turtle_dot is None:
            return

        # Given the col and row of the turtle, do something
        new_dot = self._grid_to_dot(
            self._my_strategy_import(self.strategy,
                                     self._dot_to_grid(self._turtle_dot)))
        self._move_turtle(self._dots[new_dot].get_xy())
        # And set the orientation
        self._turtle.set_shape(self._turtle_images[self._orientation])

        return new_dot

    def _test_game_over(self, new_dot):
        ''' Check to see if game is over '''
        if new_dot is None:
            return
        if self._dots[new_dot].type is None:
            # Game-over feedback
            self._once_around = False
            self.game_stop_time = time.time()
            self.gameover_flag = True
            self._happy_turtle_dance()
            self._timeout_id = GLib.timeout_add(10000, self._game_over)
            return True
        c = int(self._turtle_dot / THIRTEEN) % 2
        if self._dots[
            new_dot + CIRCLE[c][0][0] + THIRTEEN * CIRCLE[c][0][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][1][0] + THIRTEEN * CIRCLE[c][1][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][2][0] + THIRTEEN * CIRCLE[c][2][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][3][0] + THIRTEEN * CIRCLE[c][3][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][4][0] + THIRTEEN * CIRCLE[c][4][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][5][0] + THIRTEEN * CIRCLE[c][5][1]].type:
            # Game-over feedback
            for dot in self._dots:
                dot.set_label(':)')
                self.game_stop_time = time.time()
                self.gameover_flag = True
            self._timeout_id = GLib.timeout_add(4000, self._game_over)
            return True
        return False

    def _game_over(self):
        best_seconds = self.best_time % 60
        best_minutes = self.best_time // 60
        self.elapsed_time = int(self.game_stop_time - self.game_start_time)
        second = self.elapsed_time % 60
        minute = self.elapsed_time // 60
        for dot in self._dots:
            dot.hide()
        self._turtle.hide()

        offset_y = int(self._space_gameover / 4.)
        offset_x = int((self._width - 6 * self._dot_size_gameover -
                        5 * self._space_gameover) / 2.)
        y = 1.5
        for x in range(2, 6):
            self._gameover.append(
                Sprite(
                    self._sprites,
                    offset_x + (x - 0.50) * self._dot_size_gameover,
                    y * (self._dot_size + self._space) + offset_y,
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._gameover[-1].type = -1  # No image
            self._gameover[-1].set_label_attributes(72)
        text = ["☻", " Game ", " Over ", "☻"]
        self.rings(len(text), text, self._gameover)
        y = 4.5
        for x in range(2, 6):
            self._win_lose.append(
                Sprite(
                    self._sprites,
                    offset_x + (x - 0.50) * self._dot_size_gameover,
                    y * (self._dot_size + self._space) + offset_y,
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._win_lose[-1].type = -1  # No image
            self._win_lose[-1].set_label_attributes(72)
        text_win_best_time = ["☻", "  YOU  ", "  WON  ", "☻"]
        text_lose = ["☹", "   YOU   ", "  LOST  ", "☹"]
        text_win = ["☻", " GOOD ", "   JOB  ", "☻"]
        if self.game_lost:
            self.rings(len(text_lose), text_lose, self._win_lose)
        elif self.elapsed_time <= self.best_time:
            self.rings(len(text_win_best_time), text_win_best_time,
                       self._win_lose)
        else:
            self.rings(len(text_win), text_win, self._win_lose)
        y = 7.5
        for x in range(2, 5):
            self._your_time.append(
                Sprite(
                    self._sprites, offset_x + x * self._dot_size_gameover,
                    y * (self._dot_size + self._space),
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._your_time[-1].type = -1  # No image
            self._your_time[-1].set_label_attributes(72)
        text = [
            "  your  ", " time:  ", (' {:02d}:{:02d} '.format(minute, second))
        ]
        self.rings(len(text), text, self._your_time)
        y = 10.5
        for x in range(2, 5):
            self._best_time.append(
                Sprite(
                    self._sprites, offset_x + x * self._dot_size_gameover,
                    y * (self._dot_size + self._space),
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._best_time[-1].type = -1  # No image
            self._best_time[-1].set_label_attributes(72)
        if self.elapsed_time <= self.best_time and not self.game_lost:
            self.best_time = self.elapsed_time
            best_seconds = second
            best_minutes = minute
        text = [
            "  best  ", " time:  ",
            (' {:02d}:{:02d} '.format(best_minutes, best_seconds))
        ]
        self.rings(len(text), text, self._best_time)
        self.save_best_time()
        self._timeout_id = GLib.timeout_add(7000, self.new_game)

    def rings(self, num, text, shape):
        i = 0
        for x in range(num):
            shape[x].type = -1
            shape[x].set_shape(
                self._new_dot(self._colors[FILL], self._dot_size_gameover))
            shape[x].set_label(text[i])
            shape[x].set_layer(100)
            i += 1

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * THIRTEEN

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % THIRTEEN, int(dot / THIRTEEN)]

    def _happy_turtle_dance(self):
        ''' Turtle dances along the edge '''
        self.game_lost = True
        i = self._find_the_turtle()
        if i == 0:
            if self._once_around:
                return
            else:
                self._once_around = True
        _logger.debug(i)
        x, y = self._dot_to_grid(i)
        if y == 0:
            x += 1
        if x == 0:
            y -= 1
        if x == THIRTEEN - 1:
            y += 1
        if y == THIRTEEN - 1:
            x -= 1
        i = self._grid_to_dot((x, y))
        self._dots[i].set_label(':)')
        self._move_turtle(self._dots[i].get_xy())
        self._orientation += 1
        self._orientation %= 6
        self._turtle.set_shape(self._turtle_images[self._orientation])
        self._timeout_id = GLib.timeout_add(250, self._happy_turtle_dance)

    def _ordered_weights(self, pos):
        ''' Returns the list of surrounding points sorted by their
        distance to the edge '''
        dots = self._surrounding_dots(pos)
        dots_and_weights = []
        for dot in dots:
            dots_and_weights.append((dot, self._weights[dot]))
        sorted_dots = sorted(dots_and_weights, key=lambda foo: foo[1])
        for i in range(6):
            dots[i] = sorted_dots[i][0]
        return dots

    def _daylight_ahead(self, pos):
        ''' Returns true if there is a straight path to the edge from
        the current position/orientation '''
        dots = self._surrounding_dots(pos)
        while True:
            dot_type = self._dots[dots[self._orientation]].type
            if dot_type is None:
                return True
            elif dot_type:
                return False
            else:  # keep looking
                pos = self._dot_to_grid(dots[self._orientation])
                dots = self._surrounding_dots(pos)

    def _surrounding_dots(self, pos):
        ''' Returns dots surrounding a position in the grid '''
        dots = []
        evenodd = pos[1] % 2
        for i in range(6):
            col = pos[0] + CIRCLE[evenodd][i][0]
            row = pos[1] + CIRCLE[evenodd][i][1]
            dots.append(self._grid_to_dot((col, row)))
        return dots

    def _initialize_weights(self):
        ''' How many steps to an edge? '''
        self._weights = []
        for d, dot in enumerate(self._dots):
            if dot.type is None:
                self._weights.append(0)
            elif dot.type:
                self._weights.append(1000)
            else:
                pos = self._dot_to_grid(d)
                pos2 = (THIRTEEN - pos[0], THIRTEEN - pos[1])
                self._weights.append(
                    min(min(pos[0], pos2[0]), min(pos[1], pos2[1])))

    def _my_strategy_import(self, f, arg):
        ''' Run Python code passed as argument '''
        userdefined = {}
        try:
            exec(f, globals(), userdefined)
            return userdefined['_turtle_strategy'](self, arg)
        except ZeroDivisionError as e:
            self._set_label('Python zero-divide error: {}'.format(e))
        except ValueError as e:
            self._set_label('Python value error: {}'.format(e))
        except SyntaxError as e:
            self._set_label('Python syntax error: {}'.format(e))
        except NameError as e:
            self._set_label('Python name error: {}'.format(e))
        except OverflowError as e:
            self._set_label('Python overflow error: {}'.format(e))
        except TypeError as e:
            self._set_label('Python type error: {}'.format(e))
        except:
            self._set_label('Python error')
        traceback.print_exc()
        return None

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y, event.area.width,
                     event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()

    def _new_dot(self, color, dot_size):
        ''' generate a dot of a color color '''
        self._stroke = color
        self._fill = color
        self._svg_width = dot_size
        self._svg_height = dot_size
        return svg_str_to_pixbuf(
            self._header() + \
            self._circle(dot_size / 2., dot_size / 2.,
                         dot_size / 2.) + \
            self._footer())

    def _new_turtle(self):
        ''' generate a turtle '''
        self._svg_width = self._dot_size * 2
        self._svg_height = self._dot_size * 2
        self._stroke = '#101010'
        self._fill = '#404040'
        return svg_str_to_pixbuf(
            self._header() + \
            self._turtle() + \
            self._footer())

    def _rotate_turtle(self, image):
        w, h = image.get_width(), image.get_height()
        nw = nh = int(sqrt(w * w + h * h))
        for i in range(6):
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
            context = cairo.Context(surface)
            context.translate(w / 2., h / 2.)
            context.rotate((30 + i * 60) * pi / 180.)
            context.translate(-w / 2., -h / 2.)
            Gdk.cairo_set_source_pixbuf(context, image, 0, 0)
            context.rectangle(0, 0, nw, nh)
            context.fill()
            self._turtle_images.append(surface)
        self._turtle_offset = int(self._dot_size / 2.)

    def _header(self):
        return '<svg\n' + 'xmlns:svg="http://www.w3.org/2000/svg"\n' + \
            'xmlns="http://www.w3.org/2000/svg"\n' + \
            'xmlns:xlink="http://www.w3.org/1999/xlink"\n' + \
            'version="1.1"\n' +  'width="' + str(self._svg_width) +  '"\n' + \
            'height="' + str(self._svg_height) + '">\n'

    def _circle(self, r, cx, cy):
        return '<circle style="fill:' + str(self._fill) + ';stroke:' + \
            str(self._stroke) +  ';" r="' + str(r - 0.5) +  '" cx="' + \
            str(cx) + '" cy="' + str(cy) + '" />\n'

    def _footer(self):
        return '</svg>\n'

    def _turtle(self):
        svg = '<g\ntransform="scale(%.1f, %.1f)">\n' % (self._svg_width / 60.,
                                                        self._svg_height / 60.)
        svg += '%s%s%s%s%s%s%s%s' % (
            '  <path d="M 27.5 48.3 ',
            'C 26.9 48.3 26.4 48.2 25.9 48.2 L 27.2 50.5 L 28.6 48.2 ',
            'C 28.2 48.2 27.9 48.3 27.5 48.3 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 40.2 11.7 ', 'C 38.0 11.7 36.2 13.3 35.8 15.3 ',
            'C 37.7 16.7 39.3 18.4 40.5 20.5 ',
            'C 42.8 20.4 44.6 18.5 44.6 16.2 ',
            'C 44.6 13.7 42.6 11.7 40.2 11.7 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 40.7 39.9 ', 'C 39.5 42.1 37.9 44.0 35.9 45.4 ',
            'C 36.4 47.3 38.1 48.7 40.2 48.7 ',
            'C 42.6 48.7 44.6 46.7 44.6 44.3 ',
            'C 44.6 42.0 42.9 40.2 40.7 39.9 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 14.3 39.9 ', 'C 12.0 40.1 10.2 42.0 10.2 44.3 ',
            'C 10.2 46.7 12.2 48.7 14.7 48.7 ',
            'C 16.7 48.7 18.5 47.3 18.9 45.4 ',
            'C 17.1 43.9 15.5 42.1 14.3 39.9 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 19.0 15.4 ', 'C 18.7 13.3 16.9 11.7 14.7 11.7 ',
            'C 12.2 11.7 10.2 13.7 10.2 16.2 ',
            'C 10.2 18.5 12.1 20.5 14.5 20.6 ',
            'C 15.7 18.5 17.2 16.8 19.0 15.4 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 27.5 12.6 ', 'C 29.4 12.6 31.2 13.0 32.9 13.7 ',
            'C 33.7 12.6 34.1 11.3 34.1 9.9 ', 'C 34.1 6.2 31.1 3.2 27.4 3.2 ',
            'C 23.7 3.2 20.7 6.2 20.7 9.9 ',
            'C 20.7 11.3 21.2 12.7 22.0 13.7 ',
            'C 23.7 13.0 25.5 12.6 27.5 12.6 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 43.1 30.4 ', 'C 43.1 35.2 41.5 39.7 38.5 43.0 ',
            'C 35.6 46.4 31.6 48.3 27.5 48.3 ',
            'C 23.4 48.3 19.4 46.4 16.5 43.0 ',
            'C 13.5 39.7 11.9 35.2 11.9 30.4 ',
            'C 11.9 20.6 18.9 12.6 27.5 12.6 ',
            'C 36.1 12.6 43.1 20.6 43.1 30.4 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s' % (
            '   <path d="M 25.9 33.8 L 24.3 29.1 ',
            'L 27.5 26.5 L 31.1 29.2 L 29.6 33.8 Z" stroke_width="3.5" ',
            'fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 27.5 41.6 ',
            'C 23.5 41.4 22.0 39.5 22.0 39.5 L 25.5 35.4 L 30.0 35.5 ',
            'L 33.1 39.7 C 33.1 39.7 30.2 41.7 27.5 41.6 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 18.5 33.8 ',
            'C 17.6 30.9 18.6 27.0 18.6 27.0 L 22.6 29.1 L 24.1 33.8 ',
            'L 20.5 38.0 C 20.5 38.0 19.1 36.0 18.4 33.8 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 19.5 25.1 ', 'C 19.5 25.1 20.0 23.2 22.5 21.3 ',
            'C 24.7 19.7 27.0 19.6 27.0 19.6 L 26.9 24.6 L 23.4 27.3 ',
            'L 19.5 25.1 Z" stroke_width="3.5" fill="', self._stroke,
            ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 32.1 27.8 L 28.6 25.0 ',
            'L 29 19.8 C 29 19.8 30.8 19.7 33.0 21.4 ',
            'C 35.2 23.2 36.3 26.4 36.3 26.4 L 32.1 27.8 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 31.3 34.0 L 32.6 29.6 ',
            'L 36.8 28.0 C 36.8 28.0 37.5 30.7 36.8 33.7 ',
            'C 36.2 36.0 34.7 38.1 34.7 38.1 L 31.3 34.0 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '</g>\n'
        return svg

    def save_best_time(self):
        file_path = os.path.join(get_activity_root(), 'data', 'best-time')
        best_time = [180]
        if os.path.exists(file_path):
            with open(file_path, "r") as fp:
                best_time = fp.readlines()
        int_best_time = int(best_time[0])
        if not int_best_time <= self.elapsed_time and not self.game_lost:
            int_best_time = self.elapsed_time
        with open(file_path, "w") as fp:
            fp.write(str(int_best_time))

    def load_best_time(self):
        file_path = os.path.join(get_activity_root(), 'data', 'best-time')
        if os.path.exists(file_path):
            with open(file_path, "r") as fp:
                highscore = fp.readlines()
            try:
                return int(highscore[0])
            except (ValueError, IndexError) as e:
                logging.exception(e)
                return 0
        return 0
class Turtle:
    def __init__(self, turtles, turtle_name, turtle_colors=None):
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._heading = 0.0
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [
                    int(radius * sin(angle)),
                    int(radius * cos(angle) + width / 2.0)
                ]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [
                    int(radius * sin(angle) + width / 2.0),
                    int(radius * cos(angle) + width / 2.0)
                ]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                             (self._half_height * self._half_height)) / 6

    def set_remote(self):
        self._remote = True

    def get_remote(self):
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = [
                '#%06x' % (COLOR_TABLE[fill]),
                '#%06x' % (COLOR_TABLE[stroke])
            ]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def set_heading(self, heading, share=True):
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) '''
        try:
            self._heading = heading
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _update_sprite_heading(self):
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        ''' Set the pen color for this turtle. '''
        # Special case for color blocks
        if color is not None and color in COLORDICT:
            self.set_shade(COLORDICT[color][1], share)
            self.set_gray(COLORDICT[color][2], share)
            if COLORDICT[color][0] is not None:
                self.set_color(COLORDICT[color][0], share)
                color = COLORDICT[color][0]
            else:
                color = self._pen_color
        elif color is None:
            color = self._pen_color

        try:
            self._pen_color = color
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            try:
                self._pen_gray = gray
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            try:
                self._pen_shade = shade
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            try:
                self._pen_size = max(0, pen_size)
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string(
                [self._turtles.turtle_window.nick, self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates((p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                    [self._turtles.turtle_window.nick, shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move(
                (pos[0] + self.label_xy[0], pos[1] + self.label_xy[1]))

    def right(self, degrees, share=True):
        ''' Rotate turtle clockwise '''
        try:
            self._heading += degrees
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _draw_line(self, old, new, pendown):
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(
                pos1[0], pos1[1], pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def forward(self, distance, share=True):
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy()
        try:
            xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
            ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), True)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        old = self.get_xy()
        try:
            if dragging:
                xcor = x
                ycor = y
            else:
                xcor = x * self._turtles.turtle_window.coord_scale
                ycor = y * self._turtles.turtle_window.coord_scale
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [round_int(xcor), round_int(ycor)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def arc(self, a, r, share=True):
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        try:
            if a < 0:
                pos = self.larc(-a, r)
            else:
                pos = self.rarc(a, r)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([
                self._turtles.turtle_window.nick, [round_int(a),
                                                   round_int(r)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(
                        ('rarc', npos[0], npos[1], r,
                         (self._heading - 180) * DEGTOR,
                         (self._heading - 180 + a) * DEGTOR))

        self.right(a, False)
        return [
            cx - r * cos(self._heading * DEGTOR),
            cy + r * sin(self._heading * DEGTOR)
        ]

    def larc(self, a, r):
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(
                        ('larc', npos[0], npos[1], r, (self._heading) * DEGTOR,
                         (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [
            cx + r * cos(self._heading * DEGTOR),
            cy - r * sin(self._heading * DEGTOR)
        ]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        ''' Draw a pixbuf '''

        self._turtles.turtle_window.canvas.draw_pixbuf(pixbuf, a, b, x, y, w,
                                                       h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    round_int(a),
                    round_int(b),
                    round_int(pos[0]),
                    round_int(pos[1]),
                    round_int(w),
                    round_int(h),
                    round_int(width),
                    round_int(height), data
                ]
            ]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    label,
                    round_int(x),
                    round_int(y),
                    round_int(size),
                    round_int(w)
                ]
            ]))
            self._turtles.turtle_window.send_event(event)

    def get_name(self):
        return self._name

    def get_xy(self):
        return [self._x, self._y]

    def get_x(self):
        return self._x

    def get_y(self):
        return self._y

    def get_heading(self):
        return self._heading

    def get_color(self):
        return self._pen_color

    def get_gray(self):
        return self._pen_gray

    def get_shade(self):
        return self._pen_shade

    def get_pen_size(self):
        return self._pen_size

    def get_pen_state(self):
        return self._pen_state

    def get_fill(self):
        return self._pen_fill

    def get_poly_points(self):
        return self._poly_points

    def get_pixel(self):
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
class Turtle:

    def __init__(self, turtles, key, turtle_colors=None):
        """ The turtle is not a block, just a sprite with an orientation """
        self.x = 0
        self.y = 0
        self.hidden = False
        self.shapes = []
        self.custom_shapes = False
        self.type = 'turtle'
        self.name = key
        self.heading = 0
        self.pen_shade = 50
        self.pen_color = 0
        self.pen_gray = 100
        self.pen_size = 5
        self.pen_state = True
        self.label_block = None

        self._prep_shapes(key, turtles, turtle_colors)

        # Choose a random angle from which to attach the turtle label
        if turtles.sprite_list is not None:
            self.spr = Sprite(turtles.sprite_list, 0, 0, self.shapes[0])
            angle = uniform(0, pi * 4 / 3.0) # 240 degrees
            w = self.shapes[0].get_width()
            r = w * 0.67
            # Restrict angle the the sides 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(r * sin(angle)),
                                 int(r * cos(angle) + w / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(r * sin(angle) + w / 2.0),
                                 int(r * cos(angle) + w / 2.0)]
        else:
            self.spr = None
        turtles.add_to_dict(key, self)

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self.shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self.shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self.heading)

    def set_shapes(self, shapes, i=0):
        """ Reskin the turtle """
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self.shapes):
                self.shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self.shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self.tw.running_sugar)
            if self.heading == 0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2., nh / 2.)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2., -nh / 2.)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.,
                                              (nh - h) / 2.)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self.shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self.heading + 5) % 360 / (360 / SHAPES)
                self.shapes[j] = shapes[0]
        self.custom_shapes = True
        self.show()

    def reset_shapes(self):
        """ Reset the shapes to the standard turtle """
        if self.custom_shapes:
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.custom_shapes = False

    def set_heading(self, heading):
        """ Set the turtle heading (one shape per 360/SHAPES degrees) """
        self.heading = heading
        i = (int(self.heading + 5) % 360) / (360 / SHAPES)
        if not self.hidden and self.spr is not None:
            try:
                self.spr.set_shape(self.shapes[i])
            except IndexError:
                self.spr.set_shape(self.shapes[0])

    def set_color(self, color):
        """ Set the pen color for this turtle. """
        self.pen_color = color

    def set_gray(self, gray):
        """ Set the pen gray level for this turtle. """
        self.pen_gray = gray

    def set_shade(self, shade):
        """ Set the pen shade for this turtle. """
        self.pen_shade = shade

    def set_pen_size(self, pen_size):
        """ Set the pen size for this turtle. """
        self.pen_size = pen_size

    def set_pen_state(self, pen_state):
        """ Set the pen state (down==True) for this turtle. """
        self.pen_state = pen_state

    def hide(self):
        """ Hide the turtle. """
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self.hidden = True

    def show(self):
        """ Show the turtle. """
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self.hidden = False
        self.move((self.x, self.y))
        self.set_heading(self.heading)
        if self.label_block is not None:
            self.label_block.spr.move((self.x + self.label_xy[0],
                                       self.y + self.label_xy[1]))
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move(self, pos):
        """ Move the turtle. """
        self.x, self.y = int(pos[0]), int(pos[1])
        if not self.hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move((pos[0] + self.label_xy[0],
                                       pos[1] + self.label_xy[1]))
        return(self.x, self.y)

    def get_name(self):
        ''' return turtle name (key) '''
        return self.name

    def get_xy(self):
        """ Return the turtle's x, y coordinates. """
        return(self.x, self.y)

    def get_heading(self):
        """ Return the turtle's heading. """
        return(self.heading)

    def get_color(self):
        """ Return the turtle's color. """
        return(self.pen_color)

    def get_gray(self):
        """ Return the turtle's gray level. """
        return(self.pen_gray)

    def get_shade(self):
        """ Return the turtle's shade. """
        return(self.pen_shade)

    def get_pen_size(self):
        """ Return the turtle's pen size. """
        return(self.pen_size)

    def get_pen_state(self):
        """ Return the turtle's pen state. """
        return(self.pen_state)
Beispiel #15
0
class Turtle:

    def __init__(self, turtles, turtle_name, turtle_colors=None):
        #print 'class Turtle taturtle.py: def __init__'
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._3Dz = 0.0
        self._3Dx = 0.0
        self._3Dy = 0.0
        self._heading = 0.0
        self._roll = 0.0
        self._pitch = 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(radius * sin(angle)),
                                 int(radius * cos(angle) + width / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(radius * sin(angle) + width / 2.0),
                                 int(radius * cos(angle) + width / 2.0)]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        #print 'taturtle.py: def _calculate_sizes'
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                            (self._half_height * self._half_height)) / 6

    def set_remote(self):
        #print 'taturtle.py: def set_remote'
        self._remote = True

    def get_remote(self):
        #print 'taturtle.py: def get_remote'
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        #print 'taturtle.py: def _prep_shapes'
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        #print 'taturtle.py: def set_turtle_colors'
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        #print 'taturtle.py: def set_shapes'
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        #print 'taturtle.py: def reset_shapes'
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def _apply_rotations(self):
        
	self._direction = [0., 1., 0.]
	angle = self._heading * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) - (self._direction[1] * sin(angle)))
        temp.append((self._direction[0] * sin(angle)) + (self._direction[1] * cos(angle)))
        temp.append(self._direction[2] * 1.0)
        self._direction = temp[:]

	angle = self._roll * DEGTOR * -1.0
        temp = []
        temp.append(self._direction[0] * 1.0)
        temp.append((self._direction[1] * cos(angle)) - (self._direction[2] * sin(angle)))
        temp.append((self._direction[1] * sin(angle)) + (self._direction[2] * cos(angle)))
        self._direction = temp[:]

	angle = self._pitch * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) + (self._direction[2] * sin(angle)))
        temp.append(self._direction[1] * 1.0)
        temp.append((self._direction[0] * -1.0 * sin(angle)) + (self._direction[2] * cos(angle)))
        self._direction = temp[:]

    def set_heading(self, heading, share=True):
        #print 'taturtle.py: def set_heading'
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) ''' 

        self._heading = heading
        self._heading %= 360
 
        self._apply_rotations()

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)
    
    def set_roll(self, roll):
        ''' Set the turtle roll '''

        self._roll = roll
        self._roll %= 360

        self._apply_rotations()

    def set_pitch(self, pitch):
        ''' Set the turtle pitch '''

        self._pitch = pitch
        self._pitch %= 360
 
        self._apply_rotations()

    def _update_sprite_heading(self):

        #print 'taturtle.py: def _update_sprite_heading'
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        #print 'taturtle.py: def set_color'
        ''' Set the pen color for this turtle. '''
        if isinstance(color, ColorObj):
            # See comment in tatype.py TYPE_BOX -> TYPE_COLOR
            color = color.color
        if color is None:
            color = self._pen_color
        # Special case for color blocks from CONSTANTS
        elif isinstance(color, Color):
            self.set_shade(color.shade, share)
            self.set_gray(color.gray, share)
            if color.color is not None:
                color = color.color
            else:
                color = self._pen_color

        self._pen_color = color

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        #print 'taturtle.py: def set_gray'
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            self._pen_gray = gray

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        #print 'taturtle.py: def set_shade'
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            self._pen_shade = shade

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        #print 'taturtle.py: def set_pen_size'
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            self._pen_size = max(0, pen_size)

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        #print 'taturtle.py: def set_pen_state'
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        #print 'taturtle.py: def set_fill'
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        #print 'taturtle.py: def set_poly_points'
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        #print 'taturtle.py: def start_fill'
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        #print 'taturtle.py: def stop_fill'
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates(
                    (p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                        [self._turtles.turtle_window.nick,
                         shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        #print 'taturtle.py: def hide'
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        #print 'taturtle.py: def show'
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        #print 'taturtle.py: def move_turtle'
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        #print 'taturtle.py: def move_turtle_spr'
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move((pos[0] + self.label_xy[0],
                                       pos[1] + self.label_xy[1]))
    def reset_3D(self):
        self._3Dx, self._3Dy, self._3Dz = 0.0, 0.0, 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._roll, self._pitch = 0.0, 0.0
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]

    def right(self, degrees, share=True):
        #print 'taturtle.py: def right'
        ''' Rotate turtle clockwise '''
        self._heading += degrees
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def left(self, degrees, share=True):
        #print 'taturtle.py: def left'
        degrees = 0 - degrees
        self.right(degrees, share)

    def _draw_line(self, old, new, pendown):
        #print 'taturtle.py: def _draw_line'
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(pos1[0], pos1[1],
                                                         pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def draw_obj(self, file_name):

        vertices = []
        lines = []
        file_handle = open(file_name, 'r')

        for line in file_handle:
            temp = line.split()
            if temp[0] == 'v':
                vertices.append([float(temp[1]), float(temp[2]), float(temp[3])])
            if temp[0] == 'l':
                lines.append([int(temp[1]), int(temp[2])])

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height

        for line in lines:
            source = vertices[line[0] - 1]
            dest = vertices[line[1] - 1]
            
            source_point = Point3D(source[0], source[1], source[2])
            p1 = source_point.project(width, height, 512, 512)
            pair1 = [p1.x, p1.y]
            pos1 = self._turtles.screen_to_turtle_coordinates(pair1)

            dest_point = Point3D(dest[0], dest[1], dest[2])
            p2 = dest_point.project(width, height, 512, 512)
            pair2 = [p2.x, p2.y]
            pos2 = self._turtles.screen_to_turtle_coordinates(pair2)

            self._draw_line(pos1, pos2, True)
            self.move_turtle((pos2[0], pos2[1]))

        return vertices, lines

    def forward(self, distance, share=True):
        #print 'taturtle.py: def forward'
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy() #Projected Point
        old_3D = self.get_3Dpoint() #Actual Point

        #xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
        #ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)

        xcor = old_3D[0] + scaled_distance * self._direction[0]
        ycor = old_3D[1] + scaled_distance * self._direction[1]
        zcor = old_3D[2] + scaled_distance * self._direction[2]

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height
        
        old_point = Point3D(old_3D[0], old_3D[1], old_3D[2]) # Old point as Point3D object
        p = old_point.project(width, height, 512, 512) # Projected Old Point
        new_x, new_y = p.x, p.y
        pair1 = [new_x, new_y]
        pos1 = self._turtles.screen_to_turtle_coordinates(pair1)
        
        '''
        for i, val in enumerate(old_3D):
            if (abs(val) < 0.0001):
                old_3D[i] = 0.
            old_3D[i] = round(old_3D[i], 2)
        self._points.append([old_3D[0], old_3D[1], old_3D[2]])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)
        '''

        self._3Dx, self._3Dy, self._3Dz = xcor, ycor, zcor
        self.store_data()

        new_point = Point3D(xcor, ycor, zcor) # New point as 3D object
        p = new_point.project(width, height, 512, 512) # Projected New Point
        new_x, new_y = p.x, p.y
        pair2 = [new_x, new_y]
        pos2 = self._turtles.screen_to_turtle_coordinates(pair2)
        #print 'new = ', new_point.x, new_point.y, new_point.z

        self._draw_line(pos1, pos2, True)
        #self.move_turtle((xcor, ycor))
        self.move_turtle((pos2[0], pos2[1]))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def backward(self, distance, share=True):
        #print 'taturtle.py: def backward'
        distance = 0 - distance
        self.forward(distance, share)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        #print 'taturtle.py: def set_xy'
        old = self.get_xy()
        if dragging:
            xcor = x
            ycor = y
        else:
            xcor = x * self._turtles.turtle_window.coord_scale
            ycor = y * self._turtles.turtle_window.coord_scale

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(xcor),
                                               round_int(ycor)]]))
            self._turtles.turtle_window.send_event(event)

    def set_xyz(self, x, y, z):
        ''' Set the x, y and z coordinates '''

        self._3Dx, self._3Dy, self._3Dz = x, y, z
        self.store_data()
        point_3D = Point3D(x, y, z)
        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height
        p = point_3D.project(width, height, 512, 512)
        new_x, new_y = p.x, p.y
        pair = [new_x, new_y]
        pos = self._turtles.screen_to_turtle_coordinates(pair)
        self.set_xy(pos[0], pos[1])

    def store_data(self):

        if(abs(self._3Dx) < 0.0001):
            self._3Dx = 0.
        if(abs(self._3Dy) < 0.0001):
            self._3Dy = 0.
        if(abs(self._3Dz) < 0.0001):
            self._3Dz = 0.
        self._3Dx = round(self._3Dx, 2)
        self._3Dy = round(self._3Dy, 2)
        self._3Dz = round(self._3Dz, 2)

        self._points.append([self._3Dx, self._3Dy, self._3Dz])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)
    def arc(self, a, r, share=True):
        #print 'taturtle.py: def arc'
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        if a < 0:
            pos = self.larc(-a, r)
        else:
            pos = self.rarc(a, r)

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(r)]]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        #print 'taturtle.py: def rarc'
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(('rarc', npos[0], npos[1], r,
                                          (self._heading - 180) * DEGTOR,
                                          (self._heading - 180 + a) * DEGTOR))

        self.right(a, False)
        return [cx - r * cos(self._heading * DEGTOR),
                cy + r * sin(self._heading * DEGTOR)]

    def larc(self, a, r):
        #print 'taturtle.py: def larc'
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(('larc', npos[0], npos[1], r,
                                          (self._heading) * DEGTOR,
                                          (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [cx + r * cos(self._heading * DEGTOR),
                cy - r * sin(self._heading * DEGTOR)]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        #print 'taturtle.py: def draw_pixbuf'
        ''' Draw a pixbuf '''
        self._turtles.turtle_window.canvas.draw_pixbuf(
            pixbuf, a, b, x, y, w, h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(b),
                                               round_int(pos[0]),
                                               round_int(pos[1]),
                                               round_int(w), round_int(h),
                                               round_int(width),
                                               round_int(height),
                                               data]]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        #print 'taturtle.py: def draw_text'
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [label, round_int(x),
                                               round_int(y), round_int(size),
                                               round_int(w)]]))
            self._turtles.turtle_window.send_event(event)

    def read_pixel(self):
        #print 'taturtle.py: def read_pixel'
        """ Read r, g, b, a from the canvas and push b, g, r to the stack """
        r, g, b, a = self.get_pixel()
        self._turtles.turtle_window.lc.heap.append(b)
        self._turtles.turtle_window.lc.heap.append(g)
        self._turtles.turtle_window.lc.heap.append(r)

    def get_color_index(self):
        #print 'taturtle.py: def get_color_index'
        r, g, b, a = self.get_pixel()
        color_index = self._turtles.turtle_window.canvas.get_color_index(
            r, g, b)
        return color_index

    def get_name(self):
        #print 'taturtle.py: def get_name'
        return self._name

    def get_xy(self):
        #print 'taturtle.py: def get_xy'
        return [self._x, self._y]
    
    def get_3Dpoint(self):
        return [self._3Dx, self._3Dy, self._3Dz]
    
    def get_x(self):
        #print 'taturtle.py: def get_x'
        return self._3Dx

    def get_y(self):
        #print 'taturtle.py: def get_y'
        return self._3Dy

    def get_z(self):
        return self._3Dz

    def get_heading(self):
        #print 'taturtle.py: def get_heading'
        return self._heading
    
    def get_roll(self):
        return self._roll

    def get_pitch(self):
        return self._pitch

    def get_color(self):
        #print 'taturtle.py: def get_color'
        return self._pen_color

    def get_gray(self):
        #print 'taturtle.py: def get_gray'
        return self._pen_gray

    def get_shade(self):
        #print 'taturtle.py: def get_shade'
        return self._pen_shade

    def get_pen_size(self):
        #print 'taturtle.py: def get_pen_size'
        return self._pen_size

    def get_pen_state(self):
        #print 'taturtle.py: def get_pen_state'
        return self._pen_state

    def get_fill(self):
        #print 'taturtle.py: def get_fill'
        return self._pen_fill

    def get_poly_points(self):
        #print 'taturtle.py: def get_poly_points'
        return self._poly_points

    def get_pixel(self):
        #print 'taturtle.py: def get_pixel'
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        #print 'taturtle.py: def get_drag_radius'
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
Beispiel #16
0
class Spirolaterals:
    def __init__(self,
                 canvas,
                 colors,
                 parent,
                 score=0,
                 delay=500,
                 pattern=1,
                 last=None):
        self._canvas = canvas
        self._colors = colors
        self._parent = parent
        self.delay = delay
        self.score = score
        self.pattern = pattern
        self.last_pattern = last
        self._running = False

        self._turtle_canvas = None
        self._user_numbers = [1, 1, 1, 3, 2]
        self._active_index = 0

        self._sprites = Sprites(self._canvas)
        self._sprites.set_delay(True)

        size = max(Gdk.Screen.width(), Gdk.Screen.height())

        cr = self._canvas.get_property('window').cairo_create()
        self._turtle_canvas = cr.get_target().create_similar(
            cairo.CONTENT_COLOR, size, size)
        self._canvas.connect('draw', self.__draw_cb)

        self._cr = cairo.Context(self._turtle_canvas)
        self._cr.set_line_cap(1)  # Set the line cap to be round
        self._sprites.set_cairo_context(self._cr)

        self._canvas.set_can_focus(True)
        self._canvas.grab_focus()

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)

        self._canvas.connect('button-press-event', self._button_press_cb)
        self._canvas.connect('key_press_event', self._keypress_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - style.GRID_CELL_SIZE

        if self._width < self._height:
            self.i = 1
        else:
            self.i = 0

        self._calculate_scale_and_offset()

        self._numbers = []
        self._glownumbers = []
        self._create_number_sprites()
        self._create_turtle_sprites()
        self._create_results_sprites()

        self._set_color(colors[0])
        self._set_pen_size(4)

        self.reset_level()

    def _calculate_scale_and_offset(self):
        self.offset = 0
        if self.i == 0:
            self.scale = self._height / (900. - style.GRID_CELL_SIZE) * 1.25
            self.offset = (
                self._width -
                (self.sx(X1[self.i] + X2[self.i]) + self.ss(BS[self.i]))) / 2.
        else:
            self.scale = self._width / 900.
            self.offset = (self._width -
                           (self.sx(X1[self.i]) + self.ss(BS[self.i]))) / 2.

    def reset_level(self):
        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - style.GRID_CELL_SIZE
        if self._width < self._height:
            self.i = 1
        else:
            self.i = 0

        self._calculate_scale_and_offset()

        self._show_background_graphics()
        self._show_user_numbers()

        self._get_goal()
        self._draw_goal()

        self._reset_sprites()

        if self.score > 0:
            self._parent.update_score(int(self.score))

    def _reset_sprites(self):
        x = self.sx(TX[self.i] - TS[self.i] / 2)
        y = self.sy(TY[self.i])
        self._target_turtle.move((x, y))

        x = self.sx(UX[self.i] - US[self.i] / 2)
        y = self.sy(UY[self.i])
        self._user_turtles[0].move((x, y))

        for i in range(5):
            for j in range(5):
                if self.i == 0:
                    x = self.sx(
                        NX[self.i]) + i * (self.ss(NS[self.i] + NO[self.i]))
                    y = self.sy(NY[self.i])
                else:
                    x = self.sx(NX[self.i])
                    y = self.sy(
                        NY[self.i]) + i * (self.ss(NS[self.i] + NO[self.i]))
                self._numbers[i][j].move((x, y))
                self._glownumbers[i][j].move((x, y))

        x = 0
        y = self.sy(GY[self.i])
        self._success.move((x, y))
        self._success.hide()
        self._failure.move((x, y))
        self._failure.hide()
        self._splot.hide()

        if self.last_pattern == self.pattern:
            self._parent.cyan.set_sensitive(True)

    def _keypress_cb(self, area, event):
        ''' Keypress: moving the slides with the arrow keys '''

        k = Gdk.keyval_name(event.keyval)
        if k in ['1', '2', '3', '4', '5']:
            self.do_stop()
            i = self._active_index
            j = int(k) - 1
            self._numbers[i][self._user_numbers[i] - 1].set_layer(HIDDEN_LAYER)
            self._numbers[i][j].set_layer(NUMBER_LAYER)
            self._user_numbers[i] = j + 1
            self.inval(self._numbers[i][j].rect)
        elif k in ['KP_Up', 'j', 'Up']:
            self.do_stop()
            i = self._active_index
            j = self._user_numbers[i]
            if j < 5:
                j += 1
            self._numbers[i][self._user_numbers[i] - 1].set_layer(HIDDEN_LAYER)
            self._numbers[i][j - 1].set_layer(NUMBER_LAYER)
            self._user_numbers[i] = j
            self.inval(self._numbers[i][j].rect)
        elif k in ['KP_Down', 'k', 'Down']:
            self.do_stop()
            i = self._active_index
            j = self._user_numbers[i]
            if j > 0:
                j -= 1
            self._numbers[i][self._user_numbers[i] - 1].set_layer(HIDDEN_LAYER)
            self._numbers[i][j - 1].set_layer(NUMBER_LAYER)
            self._user_numbers[i] = j
            self.inval(self._numbers[i][j].rect)
        elif k in ['KP_Left', 'h', 'Left']:
            self.do_stop()
            self._active_index -= 1
            self._active_index %= 5
        elif k in ['KP_Right', 'l', 'Right']:
            self.do_stop()
            self._active_index += 1
            self._active_index %= 5
        elif k in ['Return', 'KP_Page_Up', 'KP_End']:
            self.do_run()
        elif k in ['space', 'Esc', 'KP_Page_Down', 'KP_Home']:
            self.do_stop()
        else:
            logging.debug(k)

        self._canvas.grab_focus()

    def _button_press_cb(self, win, event):
        ''' Callback to handle the button presses '''
        win.grab_focus()
        x, y = map(int, event.get_coords())
        self.press = self._sprites.find_sprite((x, y))
        if self.press is not None and self.press.type == 'number':
            self.do_stop()
            i = int(self.press.name.split(',')[0])
            self._active_index = i
            j = int(self.press.name.split(',')[1])
            j1 = (j + 1) % 5
            self._numbers[i][j1].set_layer(NUMBER_LAYER)
            self._numbers[i][j].set_layer(HIDDEN_LAYER)
            self._user_numbers[i] = j1 + 1
            self.inval(self._numbers[i][j].rect)

    def _create_results_sprites(self):
        x = 0
        y = self.sy(GY[self.i])
        self._success = Sprite(self._sprites, x, y,
                               self._parent.good_job_pixbuf())
        self._success.hide()
        self._failure = Sprite(self._sprites, x, y,
                               self._parent.try_again_pixbuf())
        self._failure.hide()

    def _create_turtle_sprites(self):
        x = self.sx(TX[self.i] - TS[self.i] / 2)
        y = self.sy(TY[self.i])
        pixbuf = self._parent.turtle_pixbuf()
        self._target_turtle = Sprite(self._sprites, x, y, pixbuf)
        self._user_turtles = []
        x = self.sx(UX[self.i] - US[self.i] / 2)
        y = self.sy(UY[self.i])
        self._user_turtles.append(Sprite(self._sprites, x, y, pixbuf))
        pixbuf = pixbuf.rotate_simple(270)
        self._user_turtles.append(Sprite(self._sprites, x, y, pixbuf))
        pixbuf = pixbuf.rotate_simple(270)
        self._user_turtles.append(Sprite(self._sprites, x, y, pixbuf))
        pixbuf = pixbuf.rotate_simple(270)
        self._user_turtles.append(Sprite(self._sprites, x, y, pixbuf))
        self._show_turtle(0)
        self._splot = Sprite(self._sprites, 0, 0, self._parent.splot_pixbuf())
        self._splot.hide()

    def _show_splot(self, x, y, dd, h):
        for i in range(4):
            self._user_turtles[i].hide()
        if h == 0:
            self._splot.move((x - int(dd / 2), y))
        elif h == 1:
            self._splot.move((x - dd, y - int(dd / 2)))
        elif h == 2:
            self._splot.move((x - int(dd / 2), y - dd))
        elif h == 3:
            self._splot.move((x, y - int(dd / 2)))
        self._splot.set_layer(SUCCESS_LAYER)
        self._failure.set_layer(SUCCESS_LAYER)

    def _show_turtle(self, t):
        for i in range(4):
            if i == t:
                self._user_turtles[i].set_layer(TURTLE_LAYER)
            else:
                self._user_turtles[i].hide()

    def _reset_user_turtle(self):
        x = self.sx(UX[self.i] - US[self.i] / 2)
        y = self.sy(UY[self.i])
        self._user_turtles[0].move((x, y))
        self._show_turtle(0)

    def _create_number_sprites(self):
        for i in range(5):
            self._numbers.append([])
            self._glownumbers.append([])
            for j in range(5):
                if self.i == 0:
                    x = self.sx(
                        NX[self.i]) + i * (self.ss(NS[self.i] + NO[self.i]))
                    y = self.sy(NY[self.i])
                else:
                    x = self.sx(NX[self.i])
                    y = self.sy(
                        NY[self.i]) + i * (self.ss(NS[self.i] + NO[self.i]))
                number = Sprite(
                    self._sprites, x, y,
                    self._parent.number_pixbuf(self.ss(NS[self.i]), j + 1,
                                               self._parent.sugarcolors[1]))
                number.type = 'number'
                number.name = '%d,%d' % (i, j)
                self._numbers[i].append(number)

                number = Sprite(
                    self._sprites, x, y,
                    self._parent.number_pixbuf(self.ss(NS[self.i]), j + 1,
                                               '#FFFFFF'))
                number.type = 'number'
                number.name = '%d,%d' % (i, j)
                self._glownumbers[i].append(number)

    def _show_user_numbers(self):
        # Hide the numbers
        for i in range(5):
            for j in range(5):
                self._numbers[i][j].set_layer(HIDDEN_LAYER)
                self._glownumbers[i][j].set_layer(HIDDEN_LAYER)
        # Show user numbers
        self._numbers[0][self._user_numbers[0] - 1].set_layer(NUMBER_LAYER)
        self._numbers[1][self._user_numbers[1] - 1].set_layer(NUMBER_LAYER)
        self._numbers[2][self._user_numbers[2] - 1].set_layer(NUMBER_LAYER)
        self._numbers[3][self._user_numbers[3] - 1].set_layer(NUMBER_LAYER)
        self._numbers[4][self._user_numbers[4] - 1].set_layer(NUMBER_LAYER)

    def _show_background_graphics(self):
        self._draw_pixbuf(self._parent.background_pixbuf(), 0, 0, self._width,
                          self._height)
        self._draw_pixbuf(self._parent.box_pixbuf(self.ss(BS[self.i])),
                          self.sx(X1[self.i]), self.sy(Y1[self.i]),
                          self.ss(BS[self.i]), self.ss(BS[self.i]))
        self._draw_pixbuf(self._parent.box_pixbuf(self.ss(BS[self.i])),
                          self.sx(X2[self.i]), self.sy(Y2[self.i]),
                          self.ss(BS[self.i]), self.ss(BS[self.i]))
        self._draw_text(self.pattern, self.sx(X1[self.i]), self.sy(Y1[self.i]),
                        self.ss(LS[self.i]))

    def _set_pen_size(self, ps):
        self._cr.set_line_width(ps)

    def _set_color(self, color):
        r = color[0] / 255.
        g = color[1] / 255.
        b = color[2] / 255.
        self._cr.set_source_rgb(r, g, b)

    def _draw_line(self, x1, y1, x2, y2):
        self._cr.move_to(x1, y1)
        self._cr.line_to(x2, y2)
        self._cr.stroke()

    def ss(self, f):  # scale size function
        return int(f * self.scale)

    def sx(self, f):  # scale x function
        return int(f * self.scale + self.offset)

    def sy(self, f):  # scale y function
        return int(f * self.scale)

    def _draw_pixbuf(self, pixbuf, x, y, w, h):
        self._cr.save()
        self._cr.translate(x + w / 2., y + h / 2.)
        self._cr.translate(-x - w / 2., -y - h / 2.)
        Gdk.cairo_set_source_pixbuf(self._cr, pixbuf, x, y)
        self._cr.rectangle(x, y, w, h)
        self._cr.fill()
        self._cr.restore()

    def _draw_text(self, label, x, y, size):
        pl = PangoCairo.create_layout(self._cr)
        fd = Pango.FontDescription('Sans')
        fd.set_size(int(size) * Pango.SCALE)
        pl.set_font_description(fd)
        if type(label) == str or type(label) == unicode:
            pl.set_text(label.replace('\0', ' '), -1)
        elif type(label) == float or type(label) == int:
            pl.set_text(str(label), -1)
        else:
            pl.set_text(str(label), -1)
        self._cr.save()
        self._cr.translate(x, y)
        self._cr.set_source_rgb(1, 1, 1)
        PangoCairo.update_layout(self._cr, pl)
        PangoCairo.show_layout(self._cr, pl)
        self._cr.restore()

    def inval(self, r):
        self._canvas.queue_draw_area(r[0], r[1], r[2], r[3])

    def inval_all(self):
        self._canvas.queue_draw_area(0, 0, self._width, self._height)

    def __draw_cb(self, canvas, cr):
        cr.set_source_surface(self._turtle_canvas)
        cr.paint()

        self._sprites.redraw_sprites(cr=cr)

    def do_stop(self):
        self._parent.green.set_sensitive(True)
        self._running = False

    def do_run(self):
        self._show_background_graphics()
        # TODO: Add turtle graphics
        self._success.hide()
        self._failure.hide()
        self._splot.hide()
        self._get_goal()
        self._draw_goal()
        self.inval_all()
        self._running = True
        self.loop = 0
        self._active_index = 0
        self.step = 0
        self._set_pen_size(4)
        self._set_color(self._colors[0])
        x1 = self.sx(UX[self.i])
        y1 = self.sy(UY[self.i])
        dd = self.ss(US[self.i])
        self._numbers[0][self._user_numbers[0] - 1].set_layer(HIDDEN_LAYER)
        self._glownumbers[0][self._user_numbers[0] - 1].set_layer(NUMBER_LAYER)
        self._user_turtles[0].move((int(x1 - dd / 2), y1))
        self._show_turtle(0)

        if self._running:
            GObject.timeout_add(self.delay, self._do_step, x1, y1, dd, 0)

    def _do_step(self, x1, y1, dd, h):
        if not self._running:
            return
        if self.loop > 3:
            return
        if h == 0:  # up
            x2 = x1
            y2 = y1 - dd
            self._user_turtles[h].move((int(x2 - dd / 2), int(y2 - dd)))
        elif h == 1:  # right
            x2 = x1 + dd
            y2 = y1
            self._user_turtles[h].move((int(x2), int(y2 - dd / 2)))
        elif h == 2:  # down
            x2 = x1
            y2 = y1 + dd
            self._user_turtles[h].move((int(x2 - dd / 2), int(y2)))
        elif h == 3:  # left
            x2 = x1 - dd
            y2 = y1
            self._user_turtles[h].move((int(x2 - dd), int(y2 - dd / 2)))
        self._show_turtle(h)

        if x2 < self.sx(X2[self.i]) or \
           x2 > self.sx(X2[self.i] + BS[self.i]) or \
           y2 < self.sy(Y2[self.i]) or \
           y2 > self.sy(Y2[self.i] + BS[self.i]):
            self.do_stop()
            self._show_splot(x2, y2, dd, h)

        self._draw_line(x1, y1, x2, y2)
        self.inval_all()
        self.step += 1
        i = self._active_index
        if self.step == self._user_numbers[i]:
            number = self._user_numbers[i] - 1
            self._numbers[i][number].set_layer(NUMBER_LAYER)
            self._glownumbers[i][number].set_layer(HIDDEN_LAYER)
            h += 1
            h %= 4
            self.step = 0
            self._active_index += 1
            if self._active_index == 5:
                self.loop += 1
                self._active_index = 0
            else:
                i = self._active_index
                number = self._user_numbers[i] - 1
                self._numbers[i][number].set_layer(HIDDEN_LAYER)
                self._glownumbers[i][number].set_layer(NUMBER_LAYER)

        if self.loop < 4 and self._running:
            GObject.timeout_add(self.delay, self._do_step, x2, y2, dd, h)
        elif self.loop == 4:  # Test to see if we win
            self._running = False
            self._parent.green.set_sensitive(True)
            self._reset_user_turtle()
            self._show_user_numbers()
            self._test_level()

    def _test_level(self):
        success = True
        for i in range(5):
            if self._user_numbers[i] != self._goal[i]:
                success = False
                break
        if success:
            self._do_success()
        else:
            self._do_fail()

    def _do_success(self):
        self._success.set_layer(SUCCESS_LAYER)
        self._parent.cyan.set_sensitive(True)
        if self.last_pattern != self.pattern:
            self.score += 6
            self.last_pattern = self.pattern
        self._parent.update_score(int(self.score))

    def _do_fail(self):
        self._failure.set_layer(SUCCESS_LAYER)
        self._parent.cyan.set_sensitive(False)

    def do_slider(self, value):
        self.delay = int(value)

    def do_button(self, bu):
        self._success.hide()
        self._failure.hide()
        if bu == 'cyan':  # Next level
            self.do_stop()
            self._splot.hide()
            self.pattern += 1
            if self.pattern == 123:
                self.pattern = 1
            self._get_goal()
            self._show_background_graphics()
            self._draw_goal()
            self._reset_user_turtle()
            self.inval_all()
            self._parent.cyan.set_sensitive(False)
        elif bu == 'green':  # Run level
            self._parent.green.set_sensitive(False)
            self.do_run()
        elif bu == 'red':  # Stop level
            self.do_stop()

    def _draw_goal(self):  # draws the left hand pattern
        x1 = self.sx(TX[self.i])
        y1 = self.sy(TY[self.i])
        dd = self.ss(TS[self.i])
        dx = 0
        dy = -dd
        for i in range(4):
            for j in self._goal:
                for k in range(j):
                    x2 = x1 + dx
                    y2 = y1 + dy
                    self._set_pen_size(4)
                    self._set_color(self._colors[0])
                    self._draw_line(x1, y1, x2, y2)
                    x1 = x2
                    y1 = y2
                if dy == -dd:
                    dx = dd
                    dy = 0
                elif dx == dd:
                    dx = 0
                    dy = dd
                elif dy == dd:
                    dx = -dd
                    dy = 0
                else:
                    dx = 0
                    dy = -dd

    def _get_goal(self):
        fname = os.path.join('data', 'patterns.dat')
        try:
            f = open(fname, 'r')
            for n in range(0, self.pattern):
                s = f.readline()
            s = s[0:5]
        except:
            s = 11132
            self.pattern = 1
        f.close
        l = [int(c) for c in str(s)]
        self._goal = l
Beispiel #17
0
class Turtle:
    def __init__(self, turtles, turtle_name, turtle_colors=None):
        #print 'class Turtle taturtle.py: def __init__'
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._3Dz = 0.0
        self._3Dx = 0.0
        self._3Dy = 0.0
        self._heading = 0.0
        self._roll = 0.0
        self._pitch = 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [
                    int(radius * sin(angle)),
                    int(radius * cos(angle) + width / 2.0)
                ]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [
                    int(radius * sin(angle) + width / 2.0),
                    int(radius * cos(angle) + width / 2.0)
                ]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        #print 'taturtle.py: def _calculate_sizes'
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                             (self._half_height * self._half_height)) / 6

    def set_remote(self):
        #print 'taturtle.py: def set_remote'
        self._remote = True

    def get_remote(self):
        #print 'taturtle.py: def get_remote'
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        #print 'taturtle.py: def _prep_shapes'
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = [
                '#%06x' % (COLOR_TABLE[fill]),
                '#%06x' % (COLOR_TABLE[stroke])
            ]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        #print 'taturtle.py: def set_turtle_colors'
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        #print 'taturtle.py: def set_shapes'
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        #print 'taturtle.py: def reset_shapes'
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def _apply_rotations(self):

        self._direction = [0., 1., 0.]
        angle = self._heading * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) -
                    (self._direction[1] * sin(angle)))
        temp.append((self._direction[0] * sin(angle)) +
                    (self._direction[1] * cos(angle)))
        temp.append(self._direction[2] * 1.0)
        self._direction = temp[:]

        angle = self._roll * DEGTOR * -1.0
        temp = []
        temp.append(self._direction[0] * 1.0)
        temp.append((self._direction[1] * cos(angle)) -
                    (self._direction[2] * sin(angle)))
        temp.append((self._direction[1] * sin(angle)) +
                    (self._direction[2] * cos(angle)))
        self._direction = temp[:]

        angle = self._pitch * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) +
                    (self._direction[2] * sin(angle)))
        temp.append(self._direction[1] * 1.0)
        temp.append((self._direction[0] * -1.0 * sin(angle)) +
                    (self._direction[2] * cos(angle)))
        self._direction = temp[:]

    def set_heading(self, heading, share=True):
        #print 'taturtle.py: def set_heading'
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) '''

        self._heading = heading
        self._heading %= 360

        self._apply_rotations()

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def set_roll(self, roll):
        ''' Set the turtle roll '''

        self._roll = roll
        self._roll %= 360

        self._apply_rotations()

    def set_pitch(self, pitch):
        ''' Set the turtle pitch '''

        self._pitch = pitch
        self._pitch %= 360

        self._apply_rotations()

    def _update_sprite_heading(self):

        #print 'taturtle.py: def _update_sprite_heading'
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        #print 'taturtle.py: def set_color'
        ''' Set the pen color for this turtle. '''
        if isinstance(color, ColorObj):
            # See comment in tatype.py TYPE_BOX -> TYPE_COLOR
            color = color.color
        if color is None:
            color = self._pen_color
        # Special case for color blocks from CONSTANTS
        elif isinstance(color, Color):
            self.set_shade(color.shade, share)
            self.set_gray(color.gray, share)
            if color.color is not None:
                color = color.color
            else:
                color = self._pen_color

        self._pen_color = color

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        #print 'taturtle.py: def set_gray'
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            self._pen_gray = gray

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        #print 'taturtle.py: def set_shade'
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            self._pen_shade = shade

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        #print 'taturtle.py: def set_pen_size'
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            self._pen_size = max(0, pen_size)

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        #print 'taturtle.py: def set_pen_state'
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string(
                [self._turtles.turtle_window.nick, self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        #print 'taturtle.py: def set_fill'
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        #print 'taturtle.py: def set_poly_points'
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        #print 'taturtle.py: def start_fill'
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        #print 'taturtle.py: def stop_fill'
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates((p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                    [self._turtles.turtle_window.nick, shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        #print 'taturtle.py: def hide'
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        #print 'taturtle.py: def show'
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        #print 'taturtle.py: def move_turtle'
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        #print 'taturtle.py: def move_turtle_spr'
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move(
                (pos[0] + self.label_xy[0], pos[1] + self.label_xy[1]))

    def reset_3D(self):
        self._3Dx, self._3Dy, self._3Dz = 0.0, 0.0, 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._roll, self._pitch = 0.0, 0.0
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]

    def right(self, degrees, share=True):
        #print 'taturtle.py: def right'
        ''' Rotate turtle clockwise '''
        self._heading += degrees
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def left(self, degrees, share=True):
        #print 'taturtle.py: def left'
        degrees = 0 - degrees
        self.right(degrees, share)

    def _draw_line(self, old, new, pendown):
        #print 'taturtle.py: def _draw_line'
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(
                pos1[0], pos1[1], pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def draw_obj(self, file_name):

        vertices = []
        lines = []
        file_handle = open(file_name, 'r')

        for line in file_handle:
            temp = line.split()
            if temp[0] == 'v':
                vertices.append(
                    [float(temp[1]),
                     float(temp[2]),
                     float(temp[3])])
            if temp[0] == 'l':
                lines.append([int(temp[1]), int(temp[2])])

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height

        for line in lines:
            source = vertices[line[0] - 1]
            dest = vertices[line[1] - 1]

            source_point = Point3D(source[0], source[1], source[2])
            p1 = source_point.project(width, height, 512, 512)
            pair1 = [p1.x, p1.y]
            pos1 = self._turtles.screen_to_turtle_coordinates(pair1)

            dest_point = Point3D(dest[0], dest[1], dest[2])
            p2 = dest_point.project(width, height, 512, 512)
            pair2 = [p2.x, p2.y]
            pos2 = self._turtles.screen_to_turtle_coordinates(pair2)

            self._draw_line(pos1, pos2, True)
            self.move_turtle((pos2[0], pos2[1]))

        return vertices, lines

    def forward(self, distance, share=True):
        #print 'taturtle.py: def forward'
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy()  #Projected Point
        old_3D = self.get_3Dpoint()  #Actual Point

        #xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
        #ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)

        xcor = old_3D[0] + scaled_distance * self._direction[0]
        ycor = old_3D[1] + scaled_distance * self._direction[1]
        zcor = old_3D[2] + scaled_distance * self._direction[2]

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height

        old_point = Point3D(old_3D[0], old_3D[1],
                            old_3D[2])  # Old point as Point3D object
        p = old_point.project(width, height, 512, 512)  # Projected Old Point
        new_x, new_y = p.x, p.y
        pair1 = [new_x, new_y]
        pos1 = self._turtles.screen_to_turtle_coordinates(pair1)
        '''
        for i, val in enumerate(old_3D):
            if (abs(val) < 0.0001):
                old_3D[i] = 0.
            old_3D[i] = round(old_3D[i], 2)
        self._points.append([old_3D[0], old_3D[1], old_3D[2]])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)
        '''

        self._3Dx, self._3Dy, self._3Dz = xcor, ycor, zcor
        self.store_data()

        new_point = Point3D(xcor, ycor, zcor)  # New point as 3D object
        p = new_point.project(width, height, 512, 512)  # Projected New Point
        new_x, new_y = p.x, p.y
        pair2 = [new_x, new_y]
        pos2 = self._turtles.screen_to_turtle_coordinates(pair2)
        #print 'new = ', new_point.x, new_point.y, new_point.z

        self._draw_line(pos1, pos2, True)
        #self.move_turtle((xcor, ycor))
        self.move_turtle((pos2[0], pos2[1]))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def backward(self, distance, share=True):
        #print 'taturtle.py: def backward'
        distance = 0 - distance
        self.forward(distance, share)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        #print 'taturtle.py: def set_xy'
        old = self.get_xy()
        if dragging:
            xcor = x
            ycor = y
        else:
            xcor = x * self._turtles.turtle_window.coord_scale
            ycor = y * self._turtles.turtle_window.coord_scale

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [round_int(xcor), round_int(ycor)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def set_xyz(self, x, y, z):
        ''' Set the x, y and z coordinates '''

        self._3Dx, self._3Dy, self._3Dz = x, y, z
        self.store_data()
        point_3D = Point3D(x, y, z)
        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height
        p = point_3D.project(width, height, 512, 512)
        new_x, new_y = p.x, p.y
        pair = [new_x, new_y]
        pos = self._turtles.screen_to_turtle_coordinates(pair)
        self.set_xy(pos[0], pos[1])

    def store_data(self):

        if (abs(self._3Dx) < 0.0001):
            self._3Dx = 0.
        if (abs(self._3Dy) < 0.0001):
            self._3Dy = 0.
        if (abs(self._3Dz) < 0.0001):
            self._3Dz = 0.
        self._3Dx = round(self._3Dx, 2)
        self._3Dy = round(self._3Dy, 2)
        self._3Dz = round(self._3Dz, 2)

        self._points.append([self._3Dx, self._3Dy, self._3Dz])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)

    def arc(self, a, r, share=True):
        #print 'taturtle.py: def arc'
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        if a < 0:
            pos = self.larc(-a, r)
        else:
            pos = self.rarc(a, r)

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([
                self._turtles.turtle_window.nick, [round_int(a),
                                                   round_int(r)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        #print 'taturtle.py: def rarc'
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(('rarc', npos[0], npos[1], r,
                                          (self._heading - 180) * DEGTOR,
                                          (self._heading - 180 + a) * DEGTOR))

        self.right(a, False)
        return [
            cx - r * cos(self._heading * DEGTOR),
            cy + r * sin(self._heading * DEGTOR)
        ]

    def larc(self, a, r):
        #print 'taturtle.py: def larc'
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(
                    ('larc', npos[0], npos[1], r, (self._heading) * DEGTOR,
                     (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [
            cx + r * cos(self._heading * DEGTOR),
            cy - r * sin(self._heading * DEGTOR)
        ]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        #print 'taturtle.py: def draw_pixbuf'
        ''' Draw a pixbuf '''
        self._turtles.turtle_window.canvas.draw_pixbuf(pixbuf, a, b, x, y, w,
                                                       h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    round_int(a),
                    round_int(b),
                    round_int(pos[0]),
                    round_int(pos[1]),
                    round_int(w),
                    round_int(h),
                    round_int(width),
                    round_int(height), data
                ]
            ]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        #print 'taturtle.py: def draw_text'
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    label,
                    round_int(x),
                    round_int(y),
                    round_int(size),
                    round_int(w)
                ]
            ]))
            self._turtles.turtle_window.send_event(event)

    def read_pixel(self):
        #print 'taturtle.py: def read_pixel'
        """ Read r, g, b, a from the canvas and push b, g, r to the stack """
        r, g, b, a = self.get_pixel()
        self._turtles.turtle_window.lc.heap.append(b)
        self._turtles.turtle_window.lc.heap.append(g)
        self._turtles.turtle_window.lc.heap.append(r)

    def get_color_index(self):
        #print 'taturtle.py: def get_color_index'
        r, g, b, a = self.get_pixel()
        color_index = self._turtles.turtle_window.canvas.get_color_index(
            r, g, b)
        return color_index

    def get_name(self):
        #print 'taturtle.py: def get_name'
        return self._name

    def get_xy(self):
        #print 'taturtle.py: def get_xy'
        return [self._x, self._y]

    def get_3Dpoint(self):
        return [self._3Dx, self._3Dy, self._3Dz]

    def get_x(self):
        #print 'taturtle.py: def get_x'
        return self._3Dx

    def get_y(self):
        #print 'taturtle.py: def get_y'
        return self._3Dy

    def get_z(self):
        return self._3Dz

    def get_heading(self):
        #print 'taturtle.py: def get_heading'
        return self._heading

    def get_roll(self):
        return self._roll

    def get_pitch(self):
        return self._pitch

    def get_color(self):
        #print 'taturtle.py: def get_color'
        return self._pen_color

    def get_gray(self):
        #print 'taturtle.py: def get_gray'
        return self._pen_gray

    def get_shade(self):
        #print 'taturtle.py: def get_shade'
        return self._pen_shade

    def get_pen_size(self):
        #print 'taturtle.py: def get_pen_size'
        return self._pen_size

    def get_pen_state(self):
        #print 'taturtle.py: def get_pen_state'
        return self._pen_state

    def get_fill(self):
        #print 'taturtle.py: def get_fill'
        return self._pen_fill

    def get_poly_points(self):
        #print 'taturtle.py: def get_poly_points'
        return self._poly_points

    def get_pixel(self):
        #print 'taturtle.py: def get_pixel'
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        #print 'taturtle.py: def get_drag_radius'
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
class BBoardActivity(activity.Activity):
    ''' Make a slideshow from starred Journal entries. '''

    def __init__(self, handle):
        ''' Initialize the toolbars and the work surface '''
        super(BBoardActivity, self).__init__(handle)

        self.datapath = get_path(activity, 'instance')

        self._hw = get_hardware()

        self._playback_buttons = {}
        self._audio_recordings = {}
        self.colors = profile.get_color().to_string().split(',')

        self._setup_toolbars()
        self._setup_canvas()

        self.slides = []
        self._setup_workspace()

        self._buddies = [profile.get_nick_name()]
        self._setup_presence_service()

        self._thumbs = []
        self._thumbnail_mode = False

        self._recording = False
        self._grecord = None
        self._alert = None

        self._dirty = False

    def _setup_canvas(self):
        ''' Create a canvas '''
        self._canvas = gtk.DrawingArea()
        self._canvas.set_size_request(int(gtk.gdk.screen_width()),
                                      int(gtk.gdk.screen_height()))
        self._canvas.show()
        self.set_canvas(self._canvas)
        self.show_all()

        self._canvas.set_flags(gtk.CAN_FOCUS)
        self._canvas.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self._canvas.add_events(gtk.gdk.POINTER_MOTION_MASK)
        self._canvas.add_events(gtk.gdk.BUTTON_RELEASE_MASK)
        self._canvas.add_events(gtk.gdk.KEY_PRESS_MASK)
        self._canvas.connect("expose-event", self._expose_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.connect("button-release-event", self._button_release_cb)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)

    def _setup_workspace(self):
        ''' Prepare to render the datastore entries. '''

        # Use the lighter color for the text background
        if lighter_color(self.colors) == 0:
            tmp = self.colors[0]
            self.colors[0] = self.colors[1]
            self.colors[1] = tmp

        self._width = gtk.gdk.screen_width()
        self._height = gtk.gdk.screen_height()
        self._scale = gtk.gdk.screen_height() / 900.

        if not HAVE_TOOLBOX and self._hw[0:2] == 'xo':
            titlef = 18
            descriptionf = 12
        else:
            titlef = 36
            descriptionf = 24

        self._find_starred()
        for ds in self.dsobjects:
            if 'title' in ds.metadata:
                title = ds.metadata['title']
            else:
                title = None
            pixbuf = None
            media_object = False
            mimetype = None
            if 'mime_type' in ds.metadata:
                mimetype = ds.metadata['mime_type']
            if mimetype[0:5] == 'image':
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                    ds.file_path, MAXX, MAXY)
                    # ds.file_path, 300, 225)
                media_object = True
            else:
                pixbuf = get_pixbuf_from_journal(ds, MAXX, MAXY)  # 300, 225)
            if 'description' in ds.metadata:
                desc = ds.metadata['description']
            else:
                desc = None
            self.slides.append(Slide(True, ds.object_id, self.colors,
                                     title, pixbuf, desc))

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        self._help = Sprite(
            self._sprites,
            int((self._width - int(PREVIEWW * self._scale)) / 2),
            int(PREVIEWY * self._scale),
            gtk.gdk.pixbuf_new_from_file_at_size(
                os.path.join(activity.get_bundle_path(), 'help.png'),
                int(PREVIEWW * self._scale), int(PREVIEWH * self._scale)))
        self._help.hide()

        self._genblanks(self.colors)

        self._title = Sprite(self._sprites, 0, 0, self._title_pixbuf)
        self._title.set_label_attributes(int(titlef * self._scale),
                                         rescale=False)
        self._preview = Sprite(self._sprites,
            int((self._width - int(PREVIEWW * self._scale)) / 2),
            int(PREVIEWY * self._scale), self._preview_pixbuf)

        self._description = Sprite(self._sprites,
                                   int(DESCRIPTIONX * self._scale),
                                   int(DESCRIPTIONY * self._scale),
                                   self._desc_pixbuf)
        self._description.set_label_attributes(int(descriptionf * self._scale))

        self._my_canvas = Sprite(self._sprites, 0, 0, self._canvas_pixbuf)
        self._my_canvas.set_layer(BOTTOM)

        self._clear_screen()

        self.i = 0
        self._show_slide()

        self._playing = False
        self._rate = 10

    def _genblanks(self, colors):
        ''' Need to cache these '''
        self._title_pixbuf = svg_str_to_pixbuf(
            genblank(self._width, int(TITLEH * self._scale), colors))
        self._preview_pixbuf = svg_str_to_pixbuf(
            genblank(int(PREVIEWW * self._scale), int(PREVIEWH * self._scale),
                     colors))
        self._desc_pixbuf = svg_str_to_pixbuf(
            genblank(int(self._width - (2 * DESCRIPTIONX * self._scale)),
                     int(DESCRIPTIONH * self._scale), colors))
        self._canvas_pixbuf = svg_str_to_pixbuf(
            genblank(self._width, self._height, (colors[0], colors[0])))

    def _setup_toolbars(self):
        ''' Setup the toolbars. '''

        self.max_participants = 6

        if HAVE_TOOLBOX:
            toolbox = ToolbarBox()

            # Activity toolbar
            activity_button_toolbar = ActivityToolbarButton(self)

            toolbox.toolbar.insert(activity_button_toolbar, 0)
            activity_button_toolbar.show()

            self.set_toolbar_box(toolbox)
            toolbox.show()
            self.toolbar = toolbox.toolbar

            self.record_toolbar = gtk.Toolbar()
            record_toolbar_button = ToolbarButton(
                label=_('Record a sound'),
                page=self.record_toolbar,
                icon_name='media-audio')
            self.record_toolbar.show_all()
            record_toolbar_button.show()
            toolbox.toolbar.insert(record_toolbar_button, -1)
        else:
            # Use pre-0.86 toolbar design
            primary_toolbar = gtk.Toolbar()
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Page'), primary_toolbar)
            self.record_toolbar = gtk.Toolbar()
            toolbox.add_toolbar(_('Record'), self.record_toolbar)
            toolbox.show()
            toolbox.set_current_toolbar(1)
            self.toolbar = primary_toolbar

        self._prev_button = button_factory(
            'go-previous-inactive', self.toolbar, self._prev_cb,
            tooltip=_('Prev slide'), accelerator='<Ctrl>P')

        self._next_button = button_factory(
            'go-next', self.toolbar, self._next_cb,
            tooltip=_('Next slide'), accelerator='<Ctrl>N')


        separator_factory(self.toolbar)

        slide_button = radio_factory('slide-view', self.toolbar,
                                     self._slides_cb, group=None,
                                     tooltip=_('Slide view'))
        radio_factory('thumbs-view', self.toolbar, self._thumbs_cb,
                      tooltip=_('Thumbnail view'),
                      group=slide_button)

        button_factory('view-fullscreen', self.toolbar,
                       self.do_fullscreen_cb, tooltip=_('Fullscreen'),
                       accelerator='<Alt>Return')

        separator_factory(self.toolbar)

        journal_button = button_factory(
            'write-journal', self.toolbar, self._do_journal_cb,
            tooltip=_('Update description'))
        self._palette = journal_button.get_palette()
        msg_box = gtk.HBox()

        sw = gtk.ScrolledWindow()
        sw.set_size_request(int(gtk.gdk.screen_width() / 2),
                            2 * style.GRID_CELL_SIZE)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._text_view = gtk.TextView()
        self._text_view.set_left_margin(style.DEFAULT_PADDING)
        self._text_view.set_right_margin(style.DEFAULT_PADDING)
        self._text_view.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self._text_view.connect('focus-out-event',
                               self._text_view_focus_out_event_cb)
        sw.add(self._text_view)
        sw.show()
        msg_box.pack_start(sw, expand=False)
        msg_box.show_all()

        self._palette.set_content(msg_box)

        label_factory(self.record_toolbar, _('Record a sound') + ':')
        self._record_button = button_factory(
            'media-record', self.record_toolbar,
            self._record_cb, tooltip=_('Start recording'))

        separator_factory(self.record_toolbar)

        # Look to see if we have audio previously recorded
        obj_id = self._get_audio_obj_id()
        dsobject = self._search_for_audio_note(obj_id)
        if dsobject is not None:
            _logger.debug('Found previously recorded audio')
            self._add_playback_button(profile.get_nick_name(),
                                      self.colors,
                                      dsobject.file_path)

        if HAVE_TOOLBOX:
            button_factory('system-restart', activity_button_toolbar,
                           self._resend_cb, tooltip=_('Refresh'))
            separator_factory(activity_button_toolbar)
            self._save_pdf = button_factory(
                'save-as-pdf', activity_button_toolbar,
                self._save_as_pdf_cb, tooltip=_('Save as PDF'))
        else:
            separator_factory(self.toolbar)
            self._save_pdf = button_factory(
                'save-as-pdf', self.toolbar,
                self._save_as_pdf_cb, tooltip=_('Save as PDF'))

        if HAVE_TOOLBOX:
            separator_factory(toolbox.toolbar, True, False)

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>q'
            toolbox.toolbar.insert(stop_button, -1)
            stop_button.show()

    def _do_journal_cb(self, button):
        self._dirty = True
        if self._palette:
            if not self._palette.is_up():
                self._palette.popup(immediate=True,
                                    state=self._palette.SECONDARY)
            else:
                self._palette.popdown(immediate=True)
            return

    def _text_view_focus_out_event_cb(self, widget, event):
        buffer = self._text_view.get_buffer()
        start_iter = buffer.get_start_iter()
        end_iter = buffer.get_end_iter()
        self.slides[self.i].desc = buffer.get_text(start_iter, end_iter)
        self._show_slide()

    def _destroy_cb(self, win, event):
        ''' Clean up on the way out. '''
        gtk.main_quit()

    def _find_starred(self):
        ''' Find all the favorites in the Journal. '''
        self.dsobjects, nobjects = datastore.find({'keep': '1'})
        _logger.debug('found %d starred items', nobjects)

    def _prev_cb(self, button=None):
        ''' The previous button has been clicked; goto previous slide. '''
        if self.i > 0:
            self.i -= 1
            self._show_slide(direction=-1)

    def _next_cb(self, button=None):
        ''' The next button has been clicked; goto next slide. '''
        if self.i < len(self.slides) - 1:
            self.i += 1
            self._show_slide()

    def _save_as_pdf_cb(self, button=None):
        ''' Export an PDF version of the slideshow to the Journal. '''
        _logger.debug('saving to PDF...')
        if 'description' in self.metadata:
            tmp_file = save_pdf(self, self._buddies,
                                description=self.metadata['description'])
        else:
            tmp_file = save_pdf(self, self._buddies)
        _logger.debug('copying PDF file to Journal...')
        dsobject = datastore.create()
        dsobject.metadata['title'] = profile.get_nick_name() + ' ' + \
                                     _('Bboard')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/pdf'
        dsobject.set_file_path(tmp_file)
        dsobject.metadata['activity'] = 'org.laptop.sugar.ReadActivity'
        datastore.write(dsobject)
        dsobject.destroy()
        return

    def _clear_screen(self):
        ''' Clear the screen to the darker of the two user colors. '''
        self._title.hide()
        self._preview.hide()
        self._description.hide()
        if hasattr(self, '_thumbs'):
            for thumbnail in self._thumbs:
                thumbnail[0].hide()
        self.invalt(0, 0, self._width, self._height)

        # Reset drag settings
        self._press = None
        self._release = None
        self._dragpos = [0, 0]
        self._total_drag = [0, 0]
        self.last_spr_moved = None

    def _update_colors(self):
        ''' Match the colors to those of the slide originator. '''
        if len(self.slides) == 0:
            return
        self._genblanks(self.slides[self.i].colors)
        self._title.set_image(self._title_pixbuf)
        self._preview.set_image(self._preview_pixbuf)
        self._description.set_image(self._desc_pixbuf)
        self._my_canvas.set_image(self._canvas_pixbuf)

    def _show_slide(self, direction=1):
        ''' Display a title, preview image, and decription for slide. '''
        self._clear_screen()
        self._update_colors()

        if len(self.slides) == 0:
            self._prev_button.set_icon('go-previous-inactive')
            self._next_button.set_icon('go-next-inactive')
            self._description.set_label(
                _('Do you have any items in your Journal starred?'))
            self._help.set_layer(TOP)
            self._description.set_layer(MIDDLE)
            return

        if self.i == 0:
            self._prev_button.set_icon('go-previous-inactive')
        else:
            self._prev_button.set_icon('go-previous')
        if self.i == len(self.slides) - 1:
            self._next_button.set_icon('go-next-inactive')
        else:
            self._next_button.set_icon('go-next')

        pixbuf = self.slides[self.i].pixbuf
        if pixbuf is not None:
            self._preview.set_shape(pixbuf.scale_simple(
                    int(PREVIEWW * self._scale),
                    int(PREVIEWH * self._scale),
                    gtk.gdk.INTERP_NEAREST))
            self._preview.set_layer(MIDDLE)
        else:
            if self._preview is not None:
                self._preview.hide()

        self._title.set_label(self.slides[self.i].title)
        self._title.set_layer(MIDDLE)

        if self.slides[self.i].desc is not None:
            self._description.set_label(self.slides[self.i].desc)
            self._description.set_layer(MIDDLE)
            text_buffer = gtk.TextBuffer()
            text_buffer.set_text(self.slides[self.i].desc)
            self._text_view.set_buffer(text_buffer)
        else:
            self._description.set_label('')
            self._description.hide()

    def _add_playback_button(self, nick, colors, audio_file):
        ''' Add a toolbar button for this audio recording '''
        if nick not in self._playback_buttons:
            self._playback_buttons[nick] = button_factory(
                'xo-chat',  self.record_toolbar,
                self._playback_recording_cb, cb_arg=nick,
                tooltip=_('Audio recording by %s') % (nick))
            xocolor = XoColor('%s,%s' % (colors[0], colors[1]))
            icon = Icon(icon_name='xo-chat', xo_color=xocolor)
            icon.show()
            self._playback_buttons[nick].set_icon_widget(icon)
            self._playback_buttons[nick].show()
        self._audio_recordings[nick] = audio_file

    def _slides_cb(self, button=None):
        if self._thumbnail_mode:
            self._thumbnail_mode = False
            self.i = self._current_slide
            self._show_slide()

    def _thumbs_cb(self, button=None):
        ''' Toggle between thumbnail view and slideshow view. '''
        if not self._thumbnail_mode:
            self._current_slide = self.i
            self._thumbnail_mode = True
            self._clear_screen()

            self._prev_button.set_icon('go-previous-inactive')
            self._next_button.set_icon('go-next-inactive')

            n = int(ceil(sqrt(len(self.slides))))
            if n > 0:
                w = int(self._width / n)
            else:
                w = self._width
            h = int(w * 0.75)  # maintain 4:3 aspect ratio
            x_off = int((self._width - n * w) / 2)
            x = x_off
            y = 0
            self._thumbs = []
            for i in range(len(self.slides)):
                self._show_thumb(i, x, y, w, h)
                x += w
                if x + w > self._width:
                    x = x_off
                    y += h
            self.i = 0  # Reset position in slideshow to the beginning
        return False

    def _show_thumb(self, i, x, y, w, h):
        ''' Display a preview image and title as a thumbnail. '''
        pixbuf = self.slides[i].pixbuf
        if pixbuf is not None:
            pixbuf_thumb = pixbuf.scale_simple(
                int(w), int(h), gtk.gdk.INTERP_TILES)
        else:
            pixbuf_thumb = svg_str_to_pixbuf(
                genblank(int(w), int(h), self.slides[i].colors))
        # Create a Sprite for this thumbnail
        self._thumbs.append([Sprite(self._sprites, x, y, pixbuf_thumb),
                             x, y, i])
        self._thumbs[i][0].set_image(
            svg_str_to_pixbuf(svg_rectangle(int(w), int(h),
                                            self.slides[i].colors)), i=1)
        self._thumbs[i][0].set_layer(TOP)

    def _expose_cb(self, win, event):
        ''' Callback to handle window expose events '''
        self.do_expose_event(event)
        return True

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

        # Create the cairo context
        cr = self.canvas.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()

        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def write_file(self, file_path):
        ''' Clean up '''
        if self._dirty:
            self._save_descriptions_cb()
            self._dirty = False
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            os.remove(os.path.join(self.datapath, 'output.ogg'))

    def do_fullscreen_cb(self, button):
        ''' Hide the Sugar toolbars. '''
        self.fullscreen()

    def invalt(self, x, y, w, h):
        ''' Mark a region for refresh '''
        self._canvas.window.invalidate_rect(
            gtk.gdk.Rectangle(int(x), int(y), int(w), int(h)), False)

    def _spr_to_thumb(self, spr):
        ''' Find which entry in the thumbnails table matches spr. '''
        for i, thumb in enumerate(self._thumbs):
            if spr == thumb[0]:
                return i
        return -1

    def _spr_is_thumbnail(self, spr):
        ''' Does spr match an entry in the thumbnails table? '''
        if self._spr_to_thumb(spr) == -1:
            return False
        else:
            return True

    def _button_press_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a thumbnail sprite? '''
        win.grab_focus()
        x, y = map(int, event.get_coords())

        self._dragpos = [x, y]
        self._total_drag = [0, 0]

        spr = self._sprites.find_sprite((x, y))
        self._press = None
        self._release = None

        # Are we clicking on a thumbnail?
        if not self._spr_is_thumbnail(spr):
            return False

        self.last_spr_moved = spr
        self._press = spr
        self._press.set_layer(DRAG)
        return False

    def _mouse_move_cb(self, win, event):
        """ Drag a thumbnail with the mouse. """
        spr = self._press
        if spr is None:
            self._dragpos = [0, 0]
            return False
        win.grab_focus()
        x, y = map(int, event.get_coords())
        dx = x - self._dragpos[0]
        dy = y - self._dragpos[1]
        spr.move_relative([dx, dy])
        # Also move the star
        self._dragpos = [x, y]
        self._total_drag[0] += dx
        self._total_drag[1] += dy
        return False

    def _button_release_cb(self, win, event):
        ''' Button event is used to swap slides or goto next slide. '''
        win.grab_focus()
        self._dragpos = [0, 0]
        x, y = map(int, event.get_coords())

        if self._thumbnail_mode:
            if self._press is None:
                return
            # Drop the dragged thumbnail below the other thumbnails so
            # that you can find the thumbnail beneath it.
            self._press.set_layer(UNDRAG)
            i = self._spr_to_thumb(self._press)
            spr = self._sprites.find_sprite((x, y))
            if self._spr_is_thumbnail(spr):
                self._release = spr
                # If we found a thumbnail and it is not the one we
                # dragged, swap their positions.
                if not self._press == self._release:
                    j = self._spr_to_thumb(self._release)
                    self._thumbs[i][0] = self._release
                    self._thumbs[j][0] = self._press
                    tmp = self.slides[i]
                    self.slides[i] = self.slides[j]
                    self.slides[j] = tmp
                    self._thumbs[j][0].move((self._thumbs[j][1],
                                             self._thumbs[j][2]))
            self._thumbs[i][0].move((self._thumbs[i][1], self._thumbs[i][2]))
            self._press.set_layer(TOP)
            self._press = None
            self._release = None
        else:
            self._next_cb()
        return False

    def _unit_combo_cb(self, arg=None):
        ''' Read value of predefined conversion factors from combo box '''
        if hasattr(self, '_unit_combo'):
            active = self._unit_combo.get_active()
            if active in UNIT_DICTIONARY:
                self._rate = UNIT_DICTIONARY[active][1]

    def _record_cb(self, button=None):
        ''' Start/stop audio recording '''
        if self._grecord is None:
            _logger.debug('setting up grecord')
            self._grecord = Grecord(self)
        if self._recording:  # Was recording, so stop (and save?)
            _logger.debug('recording...True. Preparing to save.')
            self._grecord.stop_recording_audio()
            self._recording = False
            self._record_button.set_icon('media-record')
            self._record_button.set_tooltip(_('Start recording'))
            _logger.debug('Autosaving recording')
            self._notify(title=_('Save recording'))
            gobject.timeout_add(100, self._wait_for_transcoding_to_finish)
        else:  # Wasn't recording, so start
            _logger.debug('recording...False. Start recording.')
            self._grecord.record_audio()
            self._recording = True
            self._record_button.set_icon('media-recording')
            self._record_button.set_tooltip(_('Stop recording'))

    def _wait_for_transcoding_to_finish(self, button=None):
        while not self._grecord.transcoding_complete():
            time.sleep(1)
        if self._alert is not None:
            self.remove_alert(self._alert)
            self._alert = None
        self._save_recording()

    def _playback_recording_cb(self, button=None, nick=profile.get_nick_name()):
        ''' Play back current recording '''
        _logger.debug('Playback current recording from %s...' % (nick))
        if nick in self._audio_recordings:
            play_audio_from_file(self._audio_recordings[nick])
        return

    def _get_audio_obj_id(self):
        ''' Find unique name for audio object '''
        if 'activity_id' in self.metadata:
            obj_id = self.metadata['activity_id']
        else:
            obj_id = _('Bulletin Board')
        _logger.debug(obj_id)
        return obj_id

    def _save_recording(self):
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            _logger.debug('Saving recording to Journal...')
            obj_id = self._get_audio_obj_id()
            copyfile(os.path.join(self.datapath, 'output.ogg'),
                     os.path.join(self.datapath, '%s.ogg' % (obj_id)))
            dsobject = self._search_for_audio_note(obj_id)
            if dsobject is None:
                dsobject = datastore.create()
            if dsobject is not None:
                _logger.debug(self.dsobjects[self.i].metadata['title'])
                dsobject.metadata['title'] = _('Audio recording by %s') % \
                    (self.metadata['title'])
                dsobject.metadata['icon-color'] = \
                    profile.get_color().to_string()
                dsobject.metadata['tags'] = obj_id
                dsobject.metadata['mime_type'] = 'audio/ogg'
                dsobject.set_file_path(
                    os.path.join(self.datapath, '%s.ogg' % (obj_id)))
                datastore.write(dsobject)
                dsobject.destroy()
            self._add_playback_button(
                profile.get_nick_name(), self.colors,
                os.path.join(self.datapath, '%s.ogg' % (obj_id)))
            if hasattr(self, 'chattube') and self.chattube is not None:
                self._share_audio()
        else:
            _logger.debug('Nothing to save...')
        return

    def _search_for_audio_note(self, obj_id):
        ''' Look to see if there is already a sound recorded for this
        dsobject '''
        dsobjects, nobjects = datastore.find({'mime_type': ['audio/ogg']})
        # Look for tag that matches the target object id
        for dsobject in dsobjects:
            if 'tags' in dsobject.metadata and \
               obj_id in dsobject.metadata['tags']:
                _logger.debug('Found audio note')
                return dsobject
        return None

    def _save_descriptions_cb(self, button=None):
        ''' Find the object in the datastore and write out the changes
        to the decriptions. '''
        for s in self.slides:
            if not s.owner:
                continue
            jobject = datastore.get(s.uid)
            jobject.metadata['description'] = s.desc
            datastore.write(jobject, update_mtime=False,
                            reply_handler=self.datastore_write_cb,
                            error_handler=self.datastore_write_error_cb)

    def datastore_write_cb(self):
        pass

    def datastore_write_error_cb(self, error):
        _logger.error('datastore_write_error_cb: %r' % error)

    def _notify(self, title='', msg=''):
        ''' Notify user when saves are completed '''
        self._alert = Alert()
        self._alert.props.title = title
        self._alert.props.msg = msg
        self.add_alert(self._alert)
        self._alert.show()

    def _resend_cb(self, button=None):
        ''' Resend slides, but only of sharing '''
        if hasattr(self, 'chattube') and self.chattube is not None:
            self._share_slides()
            self._share_audio()

    # Serialize

    def _dump(self, slide):
        ''' Dump data for sharing.'''
        _logger.debug('dumping %s' % (slide.uid))
        data = [slide.uid, slide.colors, slide.title,
                pixbuf_to_base64(activity, slide.pixbuf), slide.desc]
        return self._data_dumper(data)

    def _data_dumper(self, data):
        if _OLD_SUGAR_SYSTEM:
            return json.write(data)
        else:
            io = StringIO()
            jdump(data, io)
            return io.getvalue()

    def _load(self, data):
        ''' Load game data from the journal. '''
        slide = self._data_loader(data)
        if len(slide) == 5:
            if not self._slide_search(slide[0]):
                _logger.debug('loading %s' % (slide[0]))
                self.slides.append(Slide(
                        False, slide[0], slide[1], slide[2],
                        base64_to_pixbuf(activity, slide[3]), slide[4]))

    def _slide_search(self, uid):
        ''' Is this slide in the list already? '''
        for slide in self.slides:
            if slide.uid == uid:
                _logger.debug('skipping %s' % (slide.uid))
                return True
        return False

    def _data_loader(self, data):
        if _OLD_SUGAR_SYSTEM:
            return json.read(data)
        else:
            io = StringIO(data)
            return jload(io)

    # Sharing-related methods

    def _setup_presence_service(self):
        ''' Setup the Presence Service. '''
        self.pservice = presenceservice.get_instance()
        self.initiating = None  # sharing (True) or joining (False)

        owner = self.pservice.get_owner()
        self.owner = owner
        self.buddies = [owner]
        self._share = ''
        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

    def _shared_cb(self, activity):
        ''' Either set up initial share...'''
        if self._shared_activity is None:
            _logger.error('Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()')
            return

        self.initiating = True
        self.waiting = False
        _logger.debug('I am sharing...')

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan

        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal(
            'NewTube', self._new_tube_cb)

        _logger.debug('This is my activity: making a tube...')
        id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube(
            SERVICE, {})

    def _joined_cb(self, activity):
        ''' ...or join an exisiting share. '''
        if self._shared_activity is None:
            _logger.error('Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()')
            return

        self.initiating = False
        _logger.debug('I joined a shared activity.')

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan

        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal(\
            'NewTube', self._new_tube_cb)

        _logger.debug('I am joining an activity: waiting for a tube...')
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes(
            reply_handler=self._list_tubes_reply_cb,
            error_handler=self._list_tubes_error_cb)

        self.waiting = True

    def _list_tubes_reply_cb(self, tubes):
        ''' Reply to a list request. '''
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        ''' Log errors. '''
        _logger.error('ListTubes() failed: %s', e)

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        ''' Create a new tube. '''
        _logger.debug('New tube: ID=%d initator=%d type=%d service=%s '
                     'params=%r state=%d', id, initiator, type, service,
                     params, state)

        if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE):
            if state == telepathy.TUBE_STATE_LOCAL_PENDING:
                self.tubes_chan[ \
                              telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube(id)

            tube_conn = TubeConnection(self.conn,
                self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], id, \
                group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP])

            self.chattube = ChatTube(tube_conn, self.initiating, \
                self.event_received_cb)

            if self.waiting:
                self._send_event('j:%s' % (profile.get_nick_name()))

    def event_received_cb(self, text):
        ''' Data is passed as tuples: cmd:text '''
        _logger.debug('<<< %s' % (text[0]))
        if text[0] == 's':  # shared journal objects
            e, data = text.split(':')
            self._load(data)
        elif text[0] == 'j':  # Someone new has joined
            e, buddy = text.split(':')
            _logger.debug('%s has joined' % (buddy))
            if buddy not in self._buddies:
                self._buddies.append(buddy)
            if self.initiating:
                self._send_event('J:%s' % (profile.get_nick_name()))
                self._share_slides()
                self._share_audio()
        elif text[0] == 'J':  # Everyone must share
            e, buddy = text.split(':')
            self.waiting = False
            if buddy not in self._buddies:
                self._buddies.append(buddy)
                _logger.debug('%s has joined' % (buddy))
            self._share_slides()
            self._share_audio()
        elif text[0] == 'a':  # audio recording
            e, data = text.split(':')
            nick, colors, base64 = self._data_loader(data)
            path = os.path.join(activity.get_activity_root(),
                                'instance', 'nick.ogg')
            base64_to_file(activity, base64, path)
            self._add_playback_button(nick, colors, path)

    def _share_audio(self):
        if profile.get_nick_name() in self._audio_recordings:
            base64 = file_to_base64(
                    activity, self._audio_recordings[profile.get_nick_name()])
            gobject.idle_add(self._send_event, 'a:' + str(
                    self._data_dumper([profile.get_nick_name(),
                                       self.colors,
                                       base64])))

    def _share_slides(self):
        for s in self.slides:
            if s.owner:  # Maybe stagger the timing of the sends?
                gobject.idle_add(self._send_event, 's:' + str(self._dump(s)))
        _logger.debug('finished sharing')

    def _send_event(self, text):
        ''' Send event through the tube. '''
        if hasattr(self, 'chattube') and self.chattube is not None:
            _logger.debug('>>> %s' % (text[0]))
            self.chattube.SendText(text)
Beispiel #19
0
class Game():
    def __init__(self, canvas, parent=None, colors=['#A0FFA0', '#FF8080']):
        self._activity = parent
        self._colors = [colors[0]]
        self._colors.append(colors[1])
        self._colors.append('#FFFFFF')
        self._colors.append('#000000')
        self._colors.append('#FF0000')
        self._colors.append('#FF8000')
        self._colors.append('#FFFF00')
        self._colors.append('#00FF00')
        self._colors.append('#00FFFF')
        self._colors.append('#0000FF')
        self._colors.append('#FF00FF')

        self._canvas = canvas
        if parent is not None:
            parent.show_all()
            self._parent = parent

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)
        self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.connect("button-release-event", self._button_release_cb)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)
        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - GRID_CELL_SIZE

        scale = [
            self._width / (10 * DOT_SIZE * 1.2),
            self._height / (6 * DOT_SIZE * 1.2)
        ]
        self._scale = min(scale)

        self._dot_size = int(DOT_SIZE * self._scale)
        self._space = int(self._dot_size / 5.)
        self._orientation = 'horizontal'
        self.we_are_sharing = False
        self.playing_with_robot = False
        self._press = False
        self.last_spr = None
        self._timer = None
        self.roygbiv = False

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._dots = []
        for y in range(SIX):
            for x in range(TEN):
                xoffset = int((self._width - TEN * self._dot_size - \
                                   (TEN - 1) * self._space) / 2.)
                self._dots.append(
                    Sprite(self._sprites,
                           xoffset + x * (self._dot_size + self._space),
                           y * (self._dot_size + self._space),
                           self._new_dot(self._colors[2])))
                self._dots[-1].type = 2  # not set
                self._dots[-1].set_label_attributes(40)

        self.vline = Sprite(self._sprites,
                            int(self._width / 2.) - 1, 0,
                            self._line(vertical=True))
        n = SIX / 2.
        self.hline = Sprite(
            self._sprites, 0,
            int(self._dot_size * n + self._space * (n - 0.5)) - 1,
            self._line(vertical=False))
        self.hline.hide()

        # and initialize a few variables we'll need.
        self._all_clear()

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        for dot in self._dots:
            dot.type = 2
            dot.set_shape(self._new_dot(self._colors[2]))
            dot.set_label('')

        self._set_orientation()

    def _set_orientation(self):
        ''' Set bar and message for current orientation '''
        if self._orientation == 'horizontal':
            self.hline.hide()
            self.vline.set_layer(1000)
        elif self._orientation == 'vertical':
            self.hline.set_layer(1000)
            self.vline.hide()
        else:
            self.hline.set_layer(1000)
            self.vline.set_layer(1000)
        '''
        if self._orientation == 'horizontal':
            self._set_label(
                _('Click on the dots to make a horizontal reflection.'))
        elif self._orientation == 'vertical':
            self._set_label(
                _('Click on the dots to make a vertical reflection.'))
        else:
            self._set_label(
                _('Click on the dots to make a bilateral reflection.'))
        '''

    def _initiating(self):
        return self._activity.initiating

    def new_game(self, orientation='horizontal'):
        ''' Start a new game. '''
        self._orientation = orientation

        self._all_clear()

        # Fill in a few dots to start
        for i in range(int(TEN * SIX / 2)):
            n = int(uniform(0, TEN * SIX))
            if self.roygbiv:
                self._dots[n].type = int(uniform(2, len(self._colors)))
            else:
                self._dots[n].type = int(uniform(0, 4))
            self._dots[n].set_shape(
                self._new_dot(self._colors[self._dots[n].type]))

        if self.we_are_sharing:
            _logger.debug('sending a new game')
            self._parent.send_new_game()

    def restore_game(self, dot_list, orientation):
        ''' Restore a game from the Journal or share '''
        for i, dot in enumerate(dot_list):
            self._dots[i].type = dot
            self._dots[i].set_shape(
                self._new_dot(self._colors[self._dots[i].type]))
        self._orientation = orientation
        self._set_orientation()

    def save_game(self):
        ''' Return dot list and orientation for saving to Journal or
        sharing '''
        dot_list = []
        for dot in self._dots:
            dot_list.append(dot.type)
        return [dot_list, self._orientation]

    def _set_label(self, string):
        ''' Set the label in the toolbar or the window frame. '''
        self._activity.status.set_label(string)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = list(map(int, event.get_coords()))
        self._press = True

        spr = self._sprites.find_sprite((x, y))
        if spr == None:
            return True

        self.last_spr = spr
        if spr.type is not None:
            self._increment_dot(spr)
        return True

    def _button_release_cb(self, win, event):
        self._press = False
        self._stop_increment_dot()

    def _increment_dot_cb(self, spr):
        spr.type += 1
        if self.roygbiv:
            if spr.type >= len(self._colors):
                spr.type = 2
        else:
            spr.type %= 4
        spr.set_shape(self._new_dot(self._colors[spr.type]))

        if self.playing_with_robot:
            self._robot_play(spr)

        self._test_game_over()

        if self.we_are_sharing:
            _logger.debug('sending a click to the share')
            self._parent.send_dot_click(self._dots.index(spr), spr.type)

        return True  # call again

    def _increment_dot(self, spr):
        self._stop_increment_dot()

        if self._increment_dot_cb(spr):
            self._timer = GLib.timeout_add(1000, self._increment_dot_cb, spr)

    def _stop_increment_dot(self):
        if not self._timer is None:
            GLib.source_remove(self._timer)
        self._timer = None

    def _mouse_move_cb(self, win, event):
        """ Drag a tile with the mouse. """
        if not self._press:
            return
        x, y = list(map(int, event.get_coords()))
        spr = self._sprites.find_sprite((x, y))
        if spr == self.last_spr:
            return True
        if spr is None:
            return True
        if spr.type is not None:
            self.last_spr = spr
            self._increment_dot(spr)

    def _robot_play(self, dot):
        ''' Robot reflects dot clicked. '''
        x, y = self._dot_to_grid(self._dots.index(dot))
        if self._orientation == 'horizontal':
            x = TEN - x - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
        elif self._orientation == 'vertical':
            y = SIX - y - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
        else:
            x = TEN - x - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
            y = SIX - y - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
            x = TEN - x - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)

    def remote_button_press(self, dot, color):
        ''' Receive a button press from a sharer '''
        self._dots[dot].type = color
        self._dots[dot].set_shape(self._new_dot(self._colors[color]))

    def set_sharing(self, share=True):
        _logger.debug('enabling sharing')
        self.we_are_sharing = share

    def _smile(self):
        for dot in self._dots:
            dot.set_label(':)')

    def _test_game_over(self):
        ''' Check to see if game is over '''
        if self._orientation == 'horizontal':
            for y in range(SIX):
                for x in range(SIX):
                    if self._dots[y * TEN + x].type != \
                            self._dots[y * TEN + TEN - x - 1].type:
                        self._set_label(_('keep trying'))
                        return False
            self._set_label(_('good work'))
            self._smile()
            return True
        if self._orientation == 'vertical':
            for y in range(int(SIX / 2)):
                for x in range(TEN):
                    if self._dots[y * TEN + x].type != \
                            self._dots[(SIX - y - 1) * TEN + x].type:
                        self._set_label(_('keep trying'))
                        return False
            self._set_label(_('good work'))
        else:
            for y in range(SIX):
                for x in range(SIX):
                    if self._dots[y * TEN + x].type != \
                            self._dots[y * TEN + TEN - x - 1].type:
                        self._set_label(_('keep trying'))
                        return False
            for y in range(int(SIX / 2)):
                for x in range(TEN):
                    if self._dots[y * TEN + x].type != \
                            self._dots[(SIX - y - 1) * TEN + x].type:
                        self._set_label(_('keep trying'))
                        return False
            self._set_label(_('good work'))
        self._smile()
        return True

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * TEN

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % TEN, int(dot / TEN)]

    def _expose_cb(self, win, event):
        self.do_expose_event(event)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y, event.area.width,
                     event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()

    def _new_dot(self, color):
        ''' generate a dot of a color color '''
        self._dot_cache = {}
        if not color in self._dot_cache:
            self._stroke = color
            self._fill = color
            self._svg_width = self._dot_size
            self._svg_height = self._dot_size
            pixbuf = svg_str_to_pixbuf(
                self._header() + \
                self._circle(self._dot_size / 2., self._dot_size / 2.,
                             self._dot_size / 2.) + \
                self._footer())

            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self._svg_width,
                                         self._svg_height)
            context = cairo.Context(surface)
            Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
            context.rectangle(0, 0, self._svg_width, self._svg_height)
            context.fill()
            self._dot_cache[color] = surface

        return self._dot_cache[color]

    def _line(self, vertical=True):
        ''' Generate a center line '''
        if vertical:
            self._svg_width = 3
            self._svg_height = self._height
            return svg_str_to_pixbuf(
                self._header() + \
                self._rect(3, self._height, 0, 0) + \
                self._footer())
        else:
            self._svg_width = self._width
            self._svg_height = 3
            return svg_str_to_pixbuf(
                self._header() + \
                self._rect(self._width, 3, 0, 0) + \
                self._footer())

    def _header(self):
        return '<svg\n' + 'xmlns:svg="http://www.w3.org/2000/svg"\n' + \
            'xmlns="http://www.w3.org/2000/svg"\n' + \
            'xmlns:xlink="http://www.w3.org/1999/xlink"\n' + \
            'version="1.1"\n' + 'width="' + str(self._svg_width) + '"\n' + \
            'height="' + str(self._svg_height) + '">\n'

    def _rect(self, w, h, x, y):
        svg_string = '       <rect\n'
        svg_string += '          width="%f"\n' % (w)
        svg_string += '          height="%f"\n' % (h)
        svg_string += '          rx="%f"\n' % (0)
        svg_string += '          ry="%f"\n' % (0)
        svg_string += '          x="%f"\n' % (x)
        svg_string += '          y="%f"\n' % (y)
        svg_string += 'style="fill:#000000;stroke:#000000;"/>\n'
        return svg_string

    def _circle(self, r, cx, cy):
        return '<circle style="fill:' + str(self._fill) + ';stroke:' + \
            str(self._stroke) + ';" r="' + str(r - 0.5) + '" cx="' + \
            str(cx) + '" cy="' + str(cy) + '" />\n'

    def _footer(self):
        return '</svg>\n'
Beispiel #20
0
class Game():

    def __init__(self, canvas, parent=None, path=None):
        self._canvas = canvas
        self._parent = parent
        self._parent.show_all()
        self._path = path

        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)
        self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)
        self._canvas.connect('button-release-event', self._button_release_cb)
        self._canvas.add_events(Gdk.EventMask.KEY_PRESS_MASK)
        self._canvas.connect('key-press-event', self._keypress_cb)

        self._canvas.set_can_focus(True)
        self._canvas.grab_focus()

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height()
        self._scale = self._width / 1200.
        self._first_time = True
        self._loco_pos = (0, 0)
        self._loco_dim = (0, 0)
        self._loco_quadrant = 3
        self._drag_pos = [0, 0]
        self._counter = 0
        self._correct = 0
        self._timeout_id = None
        self._pause = 200
        self._press = None
        self._clicked = False
        self._dead_key = None
        self._waiting_for_delete = False
        self._waiting_for_enter = False
        self._seconds = 0
        self._timer_id = None
        self.level = 0
        self.score = 0

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        self._BG = ['background0.jpg', 'background0.jpg', 'background0.jpg',
                    'background1.jpg', 'background2.jpg', 'background2.jpg',
                    'background2.jpg']
        self._backgrounds = []
        for bg in self._BG:
            self._backgrounds.append(Sprite(
                    self._sprites, 0, 0, GdkPixbuf.Pixbuf.new_from_file_at_size(
                        os.path.join(self._path, 'images', bg),
                        self._width, self._height)))
            self._backgrounds[-1].type = 'background'
            self._backgrounds[-1].hide()

        self._panel = Sprite(
            self._sprites, int(400 * self._scale), int(400 * self._scale),
            GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'ventana.png'),
                int(720 * self._scale), int(370 * self._scale)))
        self._panel.type = 'panel'
        self._panel.set_label(LABELS[0])
        self._panel.set_label_attributes(20)
        self._panel.hide()

        self._LOCOS = glob.glob(
                os.path.join(self._path, 'images', 'loco*.png'))
        self._loco_cards = []
        for loco in self._LOCOS:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale), int(208 * self._scale))
            self._loco_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._loco_cards[-1].type = 'loco'
        self._loco_dim = (int(150 * self._scale), int(208 * self._scale))

        self._MEN = glob.glob(
                os.path.join(self._path, 'images', 'man*.png'))
        self._man_cards = []
        for loco in self._MEN:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale), int(208 * self._scale))
            self._man_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._man_cards[-1].type = 'loco'

        self._TAUNTS = glob.glob(
                os.path.join(self._path, 'images', 'taunt*.png'))
        self._taunt_cards = []
        for loco in self._TAUNTS:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale), int(208 * self._scale))
            self._taunt_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._taunt_cards[-1].type = 'loco'

        self._GHOSTS = glob.glob(
                os.path.join(self._path, 'images', 'ghost*.png'))
        self._ghost_cards = []
        for loco in self._GHOSTS:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale), int(208 * self._scale))
            self._ghost_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._ghost_cards[-1].type = 'loco'

        self._sticky_cards = []
        self._loco_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            self._LOCOS[0], int(150 * self._scale), int(208 * self._scale))
        self._man_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            self._MEN[0], int(150 * self._scale), int(208 * self._scale))
        self._ghost_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            self._GHOSTS[0], int(150 * self._scale), int(208 * self._scale))
        for i in range(len(MSGS[1])):  # Check re i18n
            self._sticky_cards.append(Sprite(self._sprites, 0, 0,
                                             self._loco_pixbuf))
            self._sticky_cards[-1].type = 'loco'
            self._sticky_cards[-1].set_label_attributes(24,
                                                        vert_align='bottom')

        self._all_clear()

    def _time_increment(self):
        ''' Track seconds since start_time. '''
        self._seconds = int(GObject.get_current_time() - self._start_time)
        self.timer_id = GObject.timeout_add(1000, self._time_increment)

    def _timer_reset(self):
        ''' Reset the timer for each level '''
        self._start_time = GObject.get_current_time()
        if self._timer_id is not None:
            GObject.source_remove(self._timer_id)
            self._timer_id = None
        self.score += self._seconds
        self._time_increment()

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        for p in self._loco_cards:
            p.hide()
        for p in self._man_cards:
            p.hide()
        for p in self._taunt_cards:
            p.hide()
        for p in self._ghost_cards:
            p.hide()
        for p in self._sticky_cards:
            p.set_shape(self._loco_pixbuf)
            p.set_label('')
            p.set_label_color('white')
            p.hide()
        self._backgrounds[self.level].set_layer(BG_LAYER)

    def _show_time(self):
        self.level = 0
        self._all_clear()
        x = int(self._width / 4.)
        y = int(self._height / 8.)
        for i in range(len(str(self.score))):
            self._sticky_cards[i].move((x, y))
            self._sticky_cards[i].set_layer(LOCO_LAYER)
            self._sticky_cards[i].set_label(str(self.score)[i])
            x += int(self._loco_dim[0] / 2.)
        self.score = 0
        self._parent.unfullscreen()
        GObject.idle_add(play_audio_from_file, self, os.path.join(
                self._path, 'sounds', 'sonar.ogg'))
        GObject.timeout_add(5000, self.new_game, True)

    def new_game(self, first_time):
        ''' Start a new game at the current level. '''
        self._first_time = first_time
        self._clicked = False

        # It may be time to advance to the next level.
        if (self.level == 6 and self._counter == len(MSGS)) or \
           self._counter > 4:
            self._first_time = True
            self.level += 1
            self._counter = 0
            self._correct = 0
            self._pause = 200
            if self.level == len(self._backgrounds):
                self._show_time()
                return

        self._all_clear()

        if self._first_time:
            # Every game starts by putting up a panel with instructions
            # The panel disappears on mouse movement
            self._panel.set_label(LABELS[self.level])
            self._panel.set_layer(PANEL_LAYER)
            play_audio_from_file(self, os.path.join(
                    self._path, 'sounds', 'drip.ogg'))
            self._timer_reset()

        if self.level == 0:
            # Choose a random location for the Loco
            self._loco_quadrant += int(uniform(1, 4))
            self._loco_quadrant %= 4
            x, y = self._quad_to_xy(self._loco_quadrant)
            play_audio_from_file(self, os.path.join(
                    self._path, 'sounds', 'bark.ogg'))
            self._loco_cards[0].move((x, y))
            self._loco_pos = (x, y)
        elif self.level == 1:
            play_audio_from_file(self, os.path.join(
                    self._path, 'sounds', 'glass.ogg'))
        elif self.level == 2:
            play_audio_from_file(self, os.path.join(
                    self._path, 'sounds', 'glass.ogg'))
            # Place some Locos on the canvas
            for i in range(self._counter + 1):
                self._loco_quadrant += int(uniform(1, 4))
                self._loco_quadrant %= 4
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
        elif self.level == 3:
            play_audio_from_file(self, os.path.join(
                    self._path, 'sounds', 'bark.ogg'))
            # Place some Locos on the left-side of the canvas
            for i in range(self._counter + 1):
                self._loco_quadrant = int(uniform(2, 4))
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
        elif self.level == 4:
            # Place some Locos on the canvas with letters as labels
            # Just lowercase
            for i in range(self._counter + 1):
                self._loco_quadrant = int(uniform(0, 4))
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
                self._sticky_cards[i].set_label(
                    ALPHABETLC[int(uniform(0, len(ALPHABETLC)))])
        elif self.level == 5:
            # Place some Locos on the canvas with letters as labels
            # Uppercase
            for i in range(self._counter + 1):
                self._loco_quadrant = int(uniform(0, 4))
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
                self._sticky_cards[i].set_label(
                    ALPHABETUC[int(uniform(0, len(ALPHABETUC)))])
        elif self.level == 6:
            x = 0
            y = 0
            c = 0
            for i in range(len(MSGS[self._counter])):
                if MSGS[self._counter][i] == ' ':
                    y += self._loco_dim[1]
                    x = 0
                else:
                    self._sticky_cards[c].move((x, y))
                    self._sticky_cards[c].type = i
                    self._sticky_cards[c].set_layer(LOCO_LAYER)
                    self._sticky_cards[c].set_label(MSGS[self._counter][i])
                    c += 1
                    x += int(self._loco_dim[0] / 2.)

        if self.level in [0, 1]:
            self._loco_quadrant += int(uniform(1, 4))
            self._loco_quadrant %= 4
            x, y = self._quad_to_xy(self._loco_quadrant)
            if self.level == 0:
                self._move_loco(x, y, 0)
            else:
                self._taunt(x, y, 0)

    def _quad_to_xy(self, q):
        x = int(max(0, (self._width / 2.) * uniform(0, 1) - self._loco_dim[0]))
        if q in [0, 1]:
            x += int(self._width / 2.)
        y = int(max(0, (self._height / 2.) * uniform(0, 1) - self._loco_dim[1]))
        if q in [1, 2]:
            y += int(self._height / 2.)
        return x, y

    def _taunt(self, x, y, i):
        n = len(self._taunt_cards)
        self._taunt_cards[(i + 1) % n].hide()
        if self._clicked:
            self._timeout_id = None
            return True
        else:
            self._taunt_cards[i % n].move((x, y))
            self._taunt_cards[i % n].set_layer(LOCO_LAYER)
            self._timeout_id = GObject.timeout_add(
                200, self._taunt, x, y, i + 1)

    def _move_loco(self, x, y, i):
        j = (i + 1) % len(self._loco_cards)
        cx, cy = self._loco_cards[i].get_xy()
        dx = cx - x
        dy = cy - y
        if dx * dx + dy * dy < 100:
            self._loco_cards[j].move((x, y))
            self._loco_pos = (x, y)
            self._loco_cards[j].hide()
            self._loco_cards[i].hide()
            self._man_cards[0].move((x, y))
            self._man_cards[0].set_layer(LOCO_LAYER)
            self._timeout_id = None
            if self._pause > 50:
                self._pause -= 10
            return True
        else:
            if dx > 0:
                cx -= 5
            elif dx < 0:
                cx += 5
            if dy > 0:
                cy -= 5
            elif dy < 0:
                cy += 5
            self._loco_cards[j].move((cx, cy))
            self._loco_pos = (cx, cy)
            self._loco_cards[j].set_layer(LOCO_LAYER)
            self._loco_cards[i].hide()
            self._timeout_id = GObject.timeout_add(
                self._pause, self._move_loco, x, y, j)

    def _keypress_cb(self, area, event):
        ''' Keypress '''
        # Games 4, 5, and 6 use the keyboard
        print 'keypress event'
        if self.level not in [4, 5, 6]:
            return True
        k = Gdk.keyval_name(event.keyval)
        u = Gdk.keyval_to_unicode(event.keyval)

        if self._waiting_for_enter:
            if k == 'Return':
                self._waiting_for_enter = False
                self._panel.hide()
                self._counter += 1
                self._correct = 0
                GObject.timeout_add(1000, self.new_game, False)
            return

        if k in NOISE_KEYS or k in WHITE_SPACE:
            return True

        if self.level == 6 and self._waiting_for_delete:
            if k in ['BackSpace', 'Delete']:
                self._waiting_for_delete = False
                self._sticky_cards[self._correct].set_label_color('white')
                self._sticky_cards[self._correct].set_label(
                    MSGS[self._counter][
                        self._sticky_cards[self._correct].type])
                self._panel.hide()
                self._panel.set_label_color('black')
            return

        if k[0:5] == 'dead_':
            self._dead_key = k[5:]
            return

        if self.level == 6:
            n = len(MSGS[self._counter])
        else:
            n = self._counter + 1

        if self.level == 6:
            i = self._correct
            if self._dead_key is not None:
                k = DEAD_DICTS[DEAD_KEYS.index(self._dead_key)][k]
                self._dead_key = None
            elif k in PUNCTUATION:
                k = PUNCTUATION[k]
            elif k in SPECIAL:
                k = SPECIAL[k]
            elif len(k) > 1:
                return True
            if self._sticky_cards[i].labels[0] == k:
                self._sticky_cards[i].set_label_color('blue')
                self._sticky_cards[i].set_label(k)
                self._correct += 1
            else:
                self._sticky_cards[i].set_label_color('red')
                self._sticky_cards[i].set_label(k)
                self._panel.set_label_color('red')
                self._panel.set_label(ALERTS[1])
                self._panel.set_layer(PANEL_LAYER)
                self._waiting_for_delete = True
                play_audio_from_file(self, os.path.join(
                        self._path, 'sounds', 'glass.ogg'))
        else:
            for i in range(n):
                if self._sticky_cards[i].labels[0] == k:
                    self._sticky_cards[i].set_label('')
                    self._sticky_cards[i].hide()
                    break

        # Test for end condition
        if self.level == 6 and \
           self._correct == len(MSGS[self._counter]) - \
                            MSGS[self._counter].count(' '):
            c = 0
            for i in range(len(MSGS[self._counter])):
                if MSGS[self._counter][i] == ' ':
                    continue
                elif MSGS[self._counter][i] != self._sticky_cards[c].labels[0]:
                    return True
                c += 1
            self._panel.set_label(ALERTS[0])
            self._panel.set_layer(PANEL_LAYER)
            self._waiting_for_enter = True
            GObject.idle_add(play_audio_from_file, self, os.path.join(
                    self._path, 'sounds', 'drip.ogg'))
            return
        else:
            for i in range(n):
                if len(self._sticky_cards[i].labels[0]) > 0:
                    return True
        self._counter += 1
        self._correct = 0
        GObject.timeout_add(1000, self.new_game, False)

    def _mouse_move_cb(self, win, event):
        ''' Move the mouse. '''
        # Games 0, 3, 4, and 5 use move events
        x, y = map(int, event.get_coords())
        if self._seconds > 1:
            self._panel.hide()
        if not self._clicked and self.level == 0:
            # For Game 0, see if the mouse is on the Loco
            dx = x - self._loco_pos[0] - self._loco_dim[0] / 2.
            dy = y - self._loco_pos[1] - self._loco_dim[1] / 2.
            if dx * dx + dy * dy < 200:
                self._clicked = True
                if self._timeout_id is not None:
                    GObject.source_remove(self._timeout_id)
                # Play again
                self._all_clear()
                self._man_cards[0].move((x - int(self._loco_dim[0] / 2.),
                                         y - int(self._loco_dim[1] / 2.)))
                self._man_cards[0].set_layer(LOCO_LAYER)
                self._correct += 1
                self._counter += 1
                GObject.timeout_add(1000, self.new_game, False)
        elif self.level in [4, 5]:
            # For Game 4 and 5, we allow dragging
            if self._press is None:
                self._drag_pos = [0, 0]
                return True
            dx = x - self._drag_pos[0]
            dy = y - self._drag_pos[1]
            self._press.move_relative((dx, dy))
            self._drag_pos = [x, y]
        elif self.level == 3:
            # For Game 3, we are dragging
            if self._press is None:
                self._drag_pos = [0, 0]
                return True
            dx = x - self._drag_pos[0]
            dy = y - self._drag_pos[1]
            self._press.move_relative((dx, dy))
            self._drag_pos = [x, y]
            if x > self._width / 2.:
                self._press.set_shape(self._man_pixbuf)
                if self._press.type == 'loco':
                    self._correct += 1
                    self._press.type = 'man'
        return True

    def _button_release_cb(self, win, event):
        # Game 3 uses release
        if self.level == 3:
            # Move to release
            if self._correct == self._counter + 1:
                self._counter += 1
                self._correct = 0
                GObject.timeout_add(2000, self.new_game, False)
        self._press = None
        self._drag_pos = [0, 0]
        return True

    def _button_press_cb(self, win, event):
        self._press = None
        x, y = map(int, event.get_coords())
        if self.level == 0:
            return
        spr = self._sprites.find_sprite((x, y))
        if spr is None:
            return
        if spr.type != 'loco':
            return
        if self.level < 2 and self._timeout_id is None:
            return
        if self._clicked:
            return

        # Games 1, 2, and 3 involve clicks; Games 4 and 5 allow click to drag
        if self.level == 1:
            self._all_clear()
            self._man_cards[0].move((x - int(self._loco_dim[0] / 2.),
                                     y - int(self._loco_dim[1] / 2.)))
            self._man_cards[0].set_layer(LOCO_LAYER)
            self._clicked = True
            self._counter += 1
            self._correct += 1
            if self._timeout_id is not None:
                GObject.source_remove(self._timeout_id)
            GObject.timeout_add(2000, self.new_game, False)
        elif self.level == 2:
            spr.set_shape(self._ghost_pixbuf)
            spr.type = 'ghost'
            if self._correct == self._counter:
                self._counter += 1
                self._correct = 0
                GObject.timeout_add(2000, self.new_game, False)
            else:
                self._correct += 1
        elif self.level in [3, 4, 5]:
            # In Games 4 and 5, dragging is used to remove overlaps
            self._press = spr
            self._drag_pos = [x, y]
        return True

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()
Beispiel #21
0
class Slide(Stator):
    """ Create a sprite for a slide """
    def __init__(self,
                 sprites,
                 path,
                 name,
                 x,
                 y,
                 w,
                 h,
                 svg_engine=None,
                 function=None):
        if svg_engine is None:
            self.spr = Sprite(sprites, x, y, file_to_pixbuf(path, name, w, h))
        else:
            self.spr = Sprite(sprites, x, y,
                              svg_str_to_pixbuf(svg_engine().svg))
        self.tab_dx = [0, SWIDTH - TABWIDTH]
        self.tab_dy = [2 * SHEIGHT, 2 * SHEIGHT]
        self.tabs = []
        self.tabs.append(
            Tab(sprites, path, 'tab', x + self.tab_dx[0], y + self.tab_dy[0],
                TABWIDTH, SHEIGHT))
        self.tabs.append(
            Tab(sprites, path, 'tab', x + self.tab_dx[1], y + self.tab_dy[1],
                TABWIDTH, SHEIGHT))
        self.calculate = function
        self.name = name

    def add_textview(self, textview, i=0):
        self.tabs[i].textview = textview
        self.tabs[i].textbuffer = textview.get_buffer()

    def set_fixed(self, fixed):
        for tab in self.tabs:
            tab.fixed = fixed

    def match(self, sprite):
        if sprite == self.spr or sprite == self.tabs[0].spr or \
                sprite == self.tabs[1].spr:
            return True
        return False

    def draw(self, layer=1000):
        self.spr.set_layer(layer)
        self.spr.draw()
        for tab in self.tabs:
            tab.draw()

    def move(self, dx, dy):
        self.spr.move((dx, dy))
        for i, tab in enumerate(self.tabs):
            tab.move(dx + self.tab_dx[i], dy + self.tab_dy[i])

    def move_relative(self, dx, dy):
        self.spr.move_relative((dx, dy))
        for i, tab in enumerate(self.tabs):
            tab.move_relative(dx, dy)

    def hide(self):
        self.spr.hide()
        for tab in self.tabs:
            tab.hide()

    def label(self, label, i=0):
        self.tabs[i].label(label)
Beispiel #22
0
class Game():
    def __init__(self,
                 canvas,
                 parent=None,
                 path=None,
                 root=None,
                 mode='array',
                 colors=['#A0FFA0', '#FF8080']):
        self._canvas = canvas
        self._parent = parent
        self._path = path
        self._root = root
        self._mode = mode
        self.current_image = 0
        self.playing = False
        self._timeout_id = None
        self._prev_mouse_pos = (0, 0)
        self._start_time = 0

        self._colors = ['#FFFFFF']
        self._colors.append(colors[0])
        self._colors.append(colors[1])

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK
                                | Gdk.EventMask.BUTTON_RELEASE_MASK
                                | Gdk.EventMask.BUTTON_MOTION_MASK
                                | Gdk.EventMask.POINTER_MOTION_MASK
                                | Gdk.EventMask.POINTER_MOTION_HINT_MASK
                                | Gdk.EventMask.TOUCH_MASK)

        self._canvas.connect('draw', self.__draw_cb)
        self._canvas.connect('event', self.__event_cb)

        self.configure(move=False)
        self.we_are_sharing = False

        self._start_time = 0
        self._timeout_id = None

        # Find the image files
        self._PATHS = glob.glob(os.path.join(self._path, 'images', '*.svg'))

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        a = max(Gdk.Screen.width(), Gdk.Screen.height())
        b = min(Gdk.Screen.width(), Gdk.Screen.height())
        self._bg_pixbufs = []
        if self._parent.tablet_mode:  # text on top
            # landscape
            self._bg_pixbufs.append(
                svg_str_to_pixbuf(
                    genhole(a, a, 3 * style.GRID_CELL_SIZE,
                            style.DEFAULT_SPACING,
                            a - 3 * style.GRID_CELL_SIZE,
                            style.GRID_CELL_SIZE * 3 + style.DEFAULT_SPACING)))
            # portrait
            self._bg_pixbufs.append(
                svg_str_to_pixbuf(
                    genhole(a, a, 3 * style.GRID_CELL_SIZE,
                            style.DEFAULT_SPACING,
                            b - 3 * style.GRID_CELL_SIZE,
                            style.GRID_CELL_SIZE * 3 + style.DEFAULT_SPACING)))
        else:  # text on bottom
            # landscape
            self._bg_pixbufs.append(
                svg_str_to_pixbuf(
                    genhole(
                        a, a, 3 * style.GRID_CELL_SIZE,
                        b - style.GRID_CELL_SIZE * 4 - style.DEFAULT_SPACING,
                        a - 3 * style.GRID_CELL_SIZE,
                        b - style.GRID_CELL_SIZE - style.DEFAULT_SPACING)))
            # portrait
            self._bg_pixbufs.append(
                svg_str_to_pixbuf(
                    genhole(
                        a, a, 3 * style.GRID_CELL_SIZE,
                        a - style.GRID_CELL_SIZE * 4 - style.DEFAULT_SPACING,
                        b - 3 * style.GRID_CELL_SIZE,
                        a - style.GRID_CELL_SIZE - style.DEFAULT_SPACING)))

        if Gdk.Screen.width() > Gdk.Screen.height():
            self._bg = Sprite(self._sprites, 0, 0, self._bg_pixbufs[0])
        else:
            self._bg = Sprite(self._sprites, 0, 0, self._bg_pixbufs[1])
        self._bg.set_layer(-2)
        self._bg.type = 'background'

        size = 3 * self._dot_size + 4 * self._space
        x = int((Gdk.Screen.width() - size) / 2.)
        self._dots = []
        self._Dots = []  # larger dots for linear mode
        X = int((Gdk.Screen.width() - self._dot_size * 3) / 2.)
        Y = style.GRID_CELL_SIZE + self._yoff
        if self._parent.tablet_mode:
            yoffset = self._space * 2 + self._yoff
        else:
            yoffset = self._yoff
        for y in range(3):
            for x in range(3):
                xoffset = int(
                    (self._width - 3 * self._dot_size - 2 * self._space) / 2.)
                self._dots.append(
                    Sprite(self._sprites,
                           xoffset + x * (self._dot_size + self._space),
                           y * (self._dot_size + self._space) + yoffset,
                           self._new_dot_surface(color=self._colors[0])))
                self._dots[-1].type = -1  # No image
                self._dots[-1].set_label_attributes(72)
                self._dots[-1].set_label('?')

                self._Dots.append(
                    Sprite(
                        self._sprites, X, Y,
                        self._new_dot_surface(color=self._colors[0],
                                              large=True)))
                self._Dots[-1].type = -1  # No image
                self._Dots[-1].set_label_attributes(72 * 3)
                self._Dots[-1].set_label('?')

        self.number_of_images = len(self._PATHS)
        if USE_ART4APPS:
            self._art4apps = Art4Apps()
            self.number_of_images = len(self._art4apps.get_words())

        self._record_pixbufs = []
        for icon in ['media-audio', 'media-audio-recording']:
            self._record_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        self._play_pixbufs = []
        for icon in ['play-inactive', 'play']:
            self._play_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        self._speak_pixbufs = []
        for icon in ['speak-inactive', 'speak']:
            self._speak_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        left = style.GRID_CELL_SIZE
        right = Gdk.Screen.width() - 2 * style.GRID_CELL_SIZE
        y0 = style.DEFAULT_SPACING + style.DEFAULT_PADDING
        y1 = y0 + style.GRID_CELL_SIZE
        y2 = y1 + style.GRID_CELL_SIZE
        if not self._parent.tablet_mode:
            dy = Gdk.Screen.height() - 4 * style.GRID_CELL_SIZE - \
                2 * style.DEFAULT_SPACING
            y0 += dy
            y1 += dy
            y2 += dy
        y3 = int((Gdk.Screen.height() - 2 * style.GRID_CELL_SIZE) / 2)

        self._record = Sprite(self._sprites, right, y0,
                              self._record_pixbufs[RECORD_OFF])
        self._record.set_layer(1)
        self._record.type = 'record'

        self._play = Sprite(self._sprites, right, y1,
                            self._play_pixbufs[PLAY_OFF])
        self._play.set_layer(1)
        self._play.type = 'play-inactive'

        self._speak = Sprite(self._sprites, right, y2,
                             self._speak_pixbufs[SPEAK_OFF])
        self._speak.set_layer(1)
        self._speak.type = 'speak-inactive'

        self._next_prev_pixbufs = []
        for icon in [
                'go-previous', 'go-next', 'go-previous-inactive',
                'go-next-inactive'
        ]:
            self._next_prev_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        self._prev = Sprite(self._sprites, left, y3,
                            self._next_prev_pixbufs[PREV_INACTIVE])
        self._prev.set_layer(1)
        self._prev.type = 'prev'
        if self._mode == 'array':
            self._prev.hide()

        self._next = Sprite(self._sprites, right, y3,
                            self._next_prev_pixbufs[NEXT])
        self._next.set_layer(1)
        self._next.type = 'next'
        if self._mode == 'array':
            self._next.hide()

    def configure(self, move=True):
        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - style.GRID_CELL_SIZE
        if not move:
            if self._height < self._width:
                self._scale = self._height / (3 * DOT_SIZE * 1.2)
            else:
                self._scale = self._width / (3 * DOT_SIZE * 1.2)
            self._scale /= 1.5
            self._dot_size = int(DOT_SIZE * self._scale)
            if self._parent.tablet_mode:  # text on top
                self._yoff = style.GRID_CELL_SIZE * 3 + style.DEFAULT_SPACING
            else:
                self._yoff = style.DEFAULT_SPACING
            self._space = int(self._dot_size / 5.)
            return

        left = style.GRID_CELL_SIZE
        right = Gdk.Screen.width() - 2 * style.GRID_CELL_SIZE
        y0 = style.DEFAULT_SPACING + style.DEFAULT_PADDING
        y1 = y0 + style.GRID_CELL_SIZE
        y2 = y1 + style.GRID_CELL_SIZE
        if not self._parent.tablet_mode:
            dy = Gdk.Screen.height() - 4 * style.GRID_CELL_SIZE - \
                2 * style.DEFAULT_SPACING
            y0 += dy
            y1 += dy
            y2 += dy
        y3 = int((Gdk.Screen.height() - 2 * style.GRID_CELL_SIZE) / 2)
        self._record.move((right, y0))
        self._play.move((right, y1))
        self._speak.move((right, y2))
        self._prev.move((left, y3))
        self._next.move((right, y3))

        # Move the dots
        X = int((Gdk.Screen.width() - self._dot_size * 3) / 2.)
        Y = style.GRID_CELL_SIZE + self._yoff
        if self._parent.tablet_mode:
            yoffset = self._space * 2 + self._yoff
        else:
            yoffset = self._yoff
        for y in range(3):
            for x in range(3):
                xoffset = int(
                    (self._width - 3 * self._dot_size - 2 * self._space) / 2.)
                self._dots[x + y * 3].move(
                    (xoffset + x * (self._dot_size + self._space),
                     y * (self._dot_size + self._space) + yoffset))
                self._Dots[x + y * 3].move((X, Y))

        # switch orientation the bg sprite
        if Gdk.Screen.width() > Gdk.Screen.height():
            self._bg.set_image(self._bg_pixbufs[0])
        else:
            self._bg.set_image(self._bg_pixbufs[1])
        self._bg.set_layer(-2)

    def set_speak_icon_state(self, state):
        if state:
            self._speak.set_image(self._speak_pixbufs[SPEAK_ON])
            self._speak.type = 'speak'
        else:
            self._speak.set_image(self._speak_pixbufs[SPEAK_OFF])
            self._speak.type = 'speak-inactive'
        self._speak.set_layer(1)

    def set_record_icon_state(self, state):
        if state:
            self._record.set_image(self._record_pixbufs[RECORD_ON])
        else:
            self._record.set_image(self._record_pixbufs[RECORD_OFF])
        self._record.set_layer(1)

    def set_play_icon_state(self, state):
        if state:
            self._play.set_image(self._play_pixbufs[PLAY_ON])
            self._play.type = 'play'
        else:
            self._play.set_image(self._play_pixbufs[PLAY_OFF])
            self._play.type = 'play-inactive'
        self._play.set_layer(1)

    def autoplay(self):
        self.set_mode('linear')  # forces current image to 0
        self.playing = True
        self._autonext(next=False)

    def stop(self):
        self.playing = False
        if self._parent.audio_process is not None:
            self._parent.audio_process.terminate()
            self._parent.audio_process = None
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)
            self._timeout_id = None
        self._parent.autoplay_button.set_icon_name('media-playback-start')
        self._parent.autoplay_button.set_tooltip(_('Play'))
        self._parent.array_button.set_sensitive(True)

    def _autonext(self, next=True):
        self._timeout_id = None
        if not self.playing:
            return

        if next:
            self._Dots[self.current_image].hide()
            self.current_image += 1
            self._Dots[self.current_image].set_layer(100)
            if self.current_image == 8:
                self._next.set_image(self._next_prev_pixbufs[NEXT_INACTIVE])
                self._next.set_layer(1)
            self._prev.set_image(self._next_prev_pixbufs[PREV])
            self._prev.set_layer(1)
        self._parent.check_audio_status()
        self._parent.check_text_status()
        GObject.idle_add(self._play_sound)

    def _poll_audio(self):
        if self._parent.audio_process is None:  # Already stopped?
            return

        if self._parent.audio_process.poll() is None:
            GObject.timeout_add(200, self._poll_audio)
        else:
            self._parent.audio_process = None
            self._next_image()

    def _play_sound(self):
        self._start_time = time.time()

        # Either play back a recording or speak the text
        if self._play.type == 'play':
            self._parent.playback_recording_cb()
            self._poll_audio()
        elif self._speak.type == 'speak':
            bounds = self._parent.text_buffer.get_bounds()
            text = self._parent.text_buffer.get_text(bounds[0], bounds[1],
                                                     True)
            speak(text)
            self._next_image()

    def _next_image(self):
        accumulated_time = int(time.time() - self._start_time)
        if accumulated_time < 5:
            pause = 5 - accumulated_time
        else:
            pause = 1
        if self.playing and self.current_image < 8:
            self._timeout_id = GObject.timeout_add(pause * 1000,
                                                   self._autonext)
        else:
            self.stop()

    def __event_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a sprite? or
            there was a gesture. '''

        left = right = False

        if event.type in (Gdk.EventType.TOUCH_BEGIN,
                          Gdk.EventType.TOUCH_CANCEL, Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_PRESS,
                          Gdk.EventType.BUTTON_RELEASE):

            x = int(event.get_coords()[1])
            y = int(event.get_coords()[2])

            if event.type in (Gdk.EventType.TOUCH_BEGIN,
                              Gdk.EventType.BUTTON_PRESS):
                self._prev_mouse_pos = (x, y)
            elif event.type in (Gdk.EventType.TOUCH_END,
                                Gdk.EventType.BUTTON_RELEASE):

                if self._parent.audio_process is not None:
                    self._parent.audio_process.terminate()
                    self._parent.audio_process = None
                    terminated_audio = True
                else:
                    terminated_audio = False

                if self.playing:
                    self.stop()

                new_mouse_pos = (x, y)
                mouse_movement = (new_mouse_pos[0] - self._prev_mouse_pos[0],
                                  new_mouse_pos[1] - self._prev_mouse_pos[1])

                # horizontal gestures only
                if (abs(mouse_movement[0]) / 5) > abs(mouse_movement[1]):
                    if abs(mouse_movement[0]) > abs(mouse_movement[1]):
                        if mouse_movement[0] < 0:
                            right = True
                        else:
                            left = True

        if event.type in (Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_RELEASE):
            spr = self._sprites.find_sprite((x, y))
            if left or right or spr is not None:
                if spr.type in [
                        'record', 'play', 'play-inactive', 'speak',
                        'speak-inactive'
                ]:
                    if spr.type == 'record':
                        self._parent.record_cb()
                    elif spr.type == 'play' and not terminated_audio:
                        self._parent.playback_recording_cb()
                    elif spr.type == 'speak':
                        bounds = self._parent.text_buffer.get_bounds()
                        text = self._parent.text_buffer.get_text(
                            bounds[0], bounds[1], True)
                        speak(text)
                    return
                elif self._mode == 'array':
                    return

                self._parent.speak_text_cb()

                if self._parent.recording:
                    self._parent.record_cb()

                if (left or spr.type == 'prev') and self.current_image > 0:
                    self._Dots[self.current_image].hide()
                    self.current_image -= 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 0:
                        self._prev.set_image(
                            self._next_prev_pixbufs[PREV_INACTIVE])
                    self._next.set_image(self._next_prev_pixbufs[NEXT])
                elif (right or spr.type == 'next') and self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                elif spr.type not in ['prev', 'background'] and \
                        self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                self._parent.check_audio_status()
                self._parent.check_text_status()
                self._prev.set_layer(1)
                self._next.set_layer(1)
        return False

    def get_mode(self):
        return self._mode

    def set_mode(self, mode):
        self.current_image = 0
        self._prev.set_image(self._next_prev_pixbufs[PREV_INACTIVE])
        self._next.set_image(self._next_prev_pixbufs[NEXT])
        if mode == 'array':
            self._mode = 'array'
            self._prev.hide()
            self._next.hide()
        else:
            self._mode = 'linear'
            self._prev.set_layer(1)
            self._next.set_layer(1)

        for i in range(9):
            if self._mode == 'array':
                self._dots[i].set_layer(100)
                self._Dots[i].hide()
            else:
                self._dots[i].hide()
                if self.current_image == i:
                    self._Dots[i].set_layer(100)
                else:
                    self._Dots[i].hide()

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)

        self.set_mode(self._mode)

        if self._mode == 'array':
            for dot in self._dots:
                if dot.type != -1:
                    dot.type = -1
                    dot.set_shape(
                        self._new_dot_surface(self._colors[abs(dot.type)]))
                    dot.set_label('?')
        else:
            for dot in self._Dots:
                if dot.type != -1:
                    dot.type = -1
                    dot.set_shape(
                        self._new_dot_surface(self._colors[abs(dot.type)],
                                              large=True))
                    dot.set_label('?')
        self._dance_counter = 0
        self._dance_step()

    def _dance_step(self):
        ''' Short animation before loading new game '''
        if self._mode == 'array':
            for dot in self._dots:
                dot.set_shape(
                    self._new_dot_surface(self._colors[int(uniform(0, 3))]))
        else:
            self._Dots[0].set_shape(
                self._new_dot_surface(self._colors[int(uniform(0, 3))],
                                      large=True))

        self._dance_counter += 1
        if self._dance_counter < 10:
            self._timeout_id = GObject.timeout_add(500, self._dance_step)
        else:
            self._new_images()

    def new_game(self):
        ''' Start a new game. '''
        self._all_clear()

    def _new_images(self):
        ''' Select pictures at random '''
        used_images = [0] * self.number_of_images
        for i in range(9):
            random_selection = int(uniform(0, self.number_of_images))
            while used_images[random_selection] != 0:
                random_selection = int(uniform(0, self.number_of_images))
            used_images[random_selection] = 1
            self._dots[i].set_label('')
            self._dots[i].type = random_selection
            self._dots[i].set_shape(
                self._new_dot_surface(image=self._dots[i].type))

            self._Dots[i].set_label('')
            self._Dots[i].type = self._dots[i].type
            self._Dots[i].set_shape(
                self._new_dot_surface(image=self._Dots[i].type, large=True))

            if self._mode == 'array':
                self._dots[i].set_layer(100)
                self._Dots[i].hide()
            else:
                if self.current_image == i:
                    self._Dots[i].set_layer(100)
                else:
                    self._Dots[i].hide()
                self._dots[i].hide()

        if self.we_are_sharing:
            self._parent.send_new_images()

    def restore_game(self, dot_list):
        ''' Restore a game from the Journal or share '''

        self.set_mode(self._mode)

        for i, dot in enumerate(dot_list):
            self._dots[i].type = dot
            self._dots[i].set_shape(
                self._new_dot_surface(image=self._dots[i].type))
            self._dots[i].set_label('')

            self._Dots[i].type = dot
            self._Dots[i].set_shape(
                self._new_dot_surface(image=self._Dots[i].type, large=True))
            self._Dots[i].set_label('')

            if self._mode == 'array':
                self._dots[i].set_layer(100)
                self._Dots[i].hide()
            else:
                if self.current_image == i:
                    self._Dots[i].set_layer(100)
                else:
                    self._Dots[i].hide()
                self._dots[i].hide()

    def save_game(self):
        ''' Return dot list for saving to Journal or
        sharing '''
        dot_list = []
        for dot in self._dots:
            dot_list.append(dot.type)
        return dot_list

    def set_sharing(self, share=True):
        self.we_are_sharing = share

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * 3

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % 3, int(dot / 3)]

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def __expose_cb(self, win, event):
        ''' Callback to handle window expose events '''
        self.do_expose_event(event)
        return True

    # Handle the expose-event by drawing
    def do_expose_event(self, event):
        # Create the cairo context
        cr = self._canvas.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y, event.area.width,
                     event.area.height)
        cr.clip()

        # Refresh sprite list
        if cr is not None:
            self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()

    def export(self):
        ''' Write dot to cairo surface. '''
        if self._mode == 'array':
            w = h = int(4 * self._space + 3 * self._dot_size)
            png_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
            cr = cairo.Context(png_surface)
            cr.set_source_rgb(192, 192, 192)
            cr.rectangle(0, 0, w, h)
            cr.fill()
            for i in range(9):
                y = self._space + int(i / 3.) * (self._dot_size + self._space)
                x = self._space + (i % 3) * (self._dot_size + self._space)
                cr.save()
                cr.set_source_surface(self._dots[i].images[0], x, y)
                cr.rectangle(x, y, self._dot_size, self._dot_size)
                cr.fill()
                cr.restore()
        else:
            w = h = int(2 * self._space + 3 * self._dot_size)
            png_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
            cr = cairo.Context(png_surface)
            cr.set_source_rgb(192, 192, 192)
            cr.rectangle(0, 0, w, h)
            cr.fill()
            y = self._space
            x = self._space
            cr.save()
            cr.set_source_surface(self._Dots[self.current_image].images[0], x,
                                  y)
            cr.rectangle(x, y, 3 * self._dot_size, 3 * self._dot_size)
            cr.fill()
            cr.restore()

        return png_surface

    def _new_dot_surface(self, color='#000000', image=None, large=False):
        ''' generate a dot of a color color '''

        if large:
            size = self._dot_size * 3
        else:
            size = self._dot_size
        self._svg_width = size
        self._svg_height = size

        if image is None:  # color dot
            self._stroke = color
            self._fill = color
            pixbuf = svg_str_to_pixbuf(self._header() +
                                       self._circle(size / 2., size /
                                                    2., size / 2.) +
                                       self._footer())
        else:
            if USE_ART4APPS:
                word = self._art4apps.get_words()[image]
                try:
                    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                        self._art4apps.get_image_filename(word), size, size)
                except Exception, e:
                    _logger.error('new dot surface %s %s: %s' %
                                  (image, word, e))
                    word = 'zebra'  # default in case image is not found
                    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                        self._art4apps.get_image_filename(word), size, size)
            else:
Beispiel #23
0
class PortfolioActivity(activity.Activity):
    ''' Make a slideshow from starred Journal entries. '''
    def __init__(self, handle):
        ''' Initialize the toolbars and the work surface '''
        super(PortfolioActivity, self).__init__(handle)

        self._tmp_path = get_path(activity, 'instance')

        self._hw = get_hardware()

        self._setup_toolbars()
        self._setup_canvas()
        self._setup_workspace()

        self._thumbs = []
        self._thumbnail_mode = False

    def _setup_canvas(self):
        ''' Create a canvas '''
        self._canvas = gtk.DrawingArea()
        self._canvas.set_size_request(gtk.gdk.screen_width(),
                                      gtk.gdk.screen_height())
        self.set_canvas(self._canvas)
        self._canvas.show()
        self.show_all()

        self._canvas.set_flags(gtk.CAN_FOCUS)
        self._canvas.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self._canvas.add_events(gtk.gdk.POINTER_MOTION_MASK)
        self._canvas.add_events(gtk.gdk.BUTTON_RELEASE_MASK)
        self._canvas.add_events(gtk.gdk.KEY_PRESS_MASK)
        self._canvas.connect("expose-event", self._expose_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.connect("button-release-event", self._button_release_cb)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)

    def _setup_workspace(self):
        ''' Prepare to render the datastore entries. '''
        self._colors = profile.get_color().to_string().split(',')

        # Use the lighter color for the text background
        if lighter_color(self._colors) == 0:
            tmp = self._colors[0]
            self._colors[0] = self._colors[1]
            self._colors[1] = tmp

        self._width = gtk.gdk.screen_width()
        self._height = gtk.gdk.screen_height()
        self._scale = gtk.gdk.screen_height() / 900.

        if self._hw[0:2] == 'xo':
            titlef = 18
            descriptionf = 12
        else:
            titlef = 36
            descriptionf = 24

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        self._title = Sprite(
            self._sprites, 0, 0,
            svg_str_to_pixbuf(
                genblank(self._width, int(TITLEH * self._scale),
                         self._colors)))
        self._title.set_label_attributes(int(titlef * self._scale),
                                         rescale=False)
        self._preview = Sprite(
            self._sprites, int(
                (self._width - int(PREVIEWW * self._scale)) / 2),
            int(PREVIEWY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(PREVIEWW * self._scale),
                         int(PREVIEWH * self._scale), self._colors)))

        self._full_screen = Sprite(
            self._sprites, int((self._width - int(FULLW * self._scale)) / 2),
            int(PREVIEWY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(FULLW * self._scale), int(FULLH * self._scale),
                         self._colors)))

        self._description = Sprite(
            self._sprites, int(DESCRIPTIONX * self._scale),
            int(DESCRIPTIONY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(self._width - (2 * DESCRIPTIONX * self._scale)),
                         int(DESCRIPTIONH * self._scale), self._colors)))
        self._description.set_label_attributes(int(descriptionf * self._scale))

        self._description2 = Sprite(
            self._sprites, int(SHORTX * self._scale),
            int(SHORTY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(self._width - (2 * SHORTX * self._scale)),
                         int(SHORTH * self._scale), self._colors)))
        self._description2.set_label_attributes(int(descriptionf *
                                                    self._scale))

        self._my_canvas = Sprite(
            self._sprites, 0, 0,
            gtk.gdk.Pixmap(self._canvas.window, self._width, self._height, -1))
        self._my_gc = self._my_canvas.images[0].new_gc()
        self._my_canvas.set_layer(BOTTOM)

        self._clear_screen()

        self._find_starred()
        self.i = 0
        self._show_slide()

        self._playing = False
        self._rate = 10

    def _setup_toolbars(self):
        ''' Setup the toolbars. '''

        self.max_participants = 1  # no sharing

        if HAVE_TOOLBOX:
            toolbox = ToolbarBox()

            # Activity toolbar
            activity_button = ActivityToolbarButton(self)

            toolbox.toolbar.insert(activity_button, 0)
            activity_button.show()

            self.set_toolbar_box(toolbox)
            toolbox.show()
            self.toolbar = toolbox.toolbar

            adjust_toolbar = gtk.Toolbar()
            adjust_toolbar_button = ToolbarButton(
                label=_('Adjust'),
                page=adjust_toolbar,
                icon_name='preferences-system')
            adjust_toolbar.show_all()
            adjust_toolbar_button.show()
        else:
            # Use pre-0.86 toolbar design
            primary_toolbar = gtk.Toolbar()
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Page'), primary_toolbar)
            adjust_toolbar = gtk.Toolbar()
            toolbox.add_toolbar(_('Adjust'), adjust_toolbar)
            toolbox.show()
            toolbox.set_current_toolbar(1)
            self.toolbar = primary_toolbar

        self._prev_button = button_factory('go-previous-inactive',
                                           _('Prev slide'),
                                           self._prev_cb,
                                           self.toolbar,
                                           accelerator='<Ctrl>P')

        self._next_button = button_factory('go-next',
                                           _('Next slide'),
                                           self._next_cb,
                                           self.toolbar,
                                           accelerator='<Ctrl>N')

        separator_factory(self.toolbar)

        self._auto_button = button_factory('media-playlist-repeat',
                                           _('Autoplay'), self._autoplay_cb,
                                           self.toolbar)

        if HAVE_TOOLBOX:
            toolbox.toolbar.insert(adjust_toolbar_button, -1)

        label = label_factory(_('Adjust playback speed'), adjust_toolbar)
        label.show()

        self._unit_combo = combo_factory(UNITS, TEN,
                                         _('Adjust playback speed'),
                                         self._unit_combo_cb, adjust_toolbar)
        self._unit_combo.show()

        separator_factory(self.toolbar)

        self._thumb_button = button_factory('thumbs-view', _('Thumbnail view'),
                                            self._thumbs_cb, self.toolbar)

        button_factory('view-fullscreen',
                       _('Fullscreen'),
                       self.do_fullscreen_cb,
                       self.toolbar,
                       accelerator='<Alt>Return')

        separator_factory(self.toolbar)

        self._save_button = button_factory('save-as-html', _('Save as HTML'),
                                           self._save_as_html_cb, self.toolbar)

        if HAVE_TOOLBOX:
            separator_factory(toolbox.toolbar, False, True)

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>q'
            toolbox.toolbar.insert(stop_button, -1)
            stop_button.show()

    def _expose_cb(self, win, event):
        ''' Have to refresh after a change in window status. '''
        self._sprites.redraw_sprites()
        return True

    def _destroy_cb(self, win, event):
        ''' Clean up on the way out. '''
        gtk.main_quit()

    def _find_starred(self):
        ''' Find all the favorites in the Journal. '''
        self._dsobjects, self._nobjects = datastore.find({'keep': '1'})
        return

    def _prev_cb(self, button=None):
        ''' The previous button has been clicked; goto previous slide. '''
        if self.i > 0:
            self.i -= 1
            self._show_slide()

    def _next_cb(self, button=None):
        ''' The next button has been clicked; goto next slide. '''
        if self.i < self._nobjects - 1:
            self.i += 1
            self._show_slide()

    def _autoplay_cb(self, button=None):
        ''' The autoplay button has been clicked; step through slides. '''
        if self._playing:
            self._stop_autoplay()
        else:
            if self._thumbnail_mode:
                self._set_view_mode(self._current_slide)
            self._playing = True
            self._auto_button.set_icon('media-playback-pause')
            self._loop()

    def _stop_autoplay(self):
        ''' Stop autoplaying. '''
        self._playing = False
        self._auto_button.set_icon('media-playlist-repeat')
        if hasattr(self, '_timeout_id') and self._timeout_id is not None:
            gobject.source_remove(self._timeout_id)

    def _loop(self):
        ''' Show a slide and then call oneself with a timeout. '''
        self.i += 1
        if self.i == self._nobjects:
            self.i = 0
        self._show_slide()
        self._timeout_id = gobject.timeout_add(int(self._rate * 1000),
                                               self._loop)

    def _bump_test(self):
        ''' Test for accelerometer event (XO 1.75 only). '''
        fh = open('/sys/devices/platform/lis3lv02d/position')
        string = fh.read()
        xyz = string[1:-2].split(',')
        dx = int(xyz[0])
        fh.close()

        if dx > 250:
            self.i += 1
            if self.i == self._nobjects:
                self.i = 0
            self._show_slide()
        elif dx < -250:
            self.i -= 1
            if self.i < 0:
                self.i = self._nobjects - 1
            self._show_slide()
        elif not self._thumbnail_mode:
            self._bump_id = gobject.timeout_add(int(100), self._bump_test)

    def _save_as_html_cb(self, button=None):
        ''' Export an HTML version of the slideshow to the Journal. '''
        self._save_button.set_icon('save-in-progress')
        results = save_html(self._dsobjects, profile.get_nick_name(),
                            self._colors, self._tmp_path)
        html_file = os.path.join(self._tmp_path, 'tmp.html')
        tmp_file = open(html_file, 'w')
        tmp_file.write(results)
        tmp_file.close()

        dsobject = datastore.create()
        dsobject.metadata['title'] = profile.get_nick_name() + ' ' + \
                                     _('Portfolio')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'text/html'
        dsobject.set_file_path(html_file)
        dsobject.metadata['activity'] = 'org.laptop.WebActivity'
        datastore.write(dsobject)
        dsobject.destroy()

        gobject.timeout_add(250, self._save_button.set_icon, 'save-as-html')
        return

    def _clear_screen(self):
        ''' Clear the screen to the darker of the two XO colors. '''
        self._my_gc.set_foreground(self._my_gc.get_colormap().alloc_color(
            self._colors[0]))
        self._my_canvas.images[0].draw_rectangle(self._my_gc, True, 0, 0,
                                                 self._width, self._height)
        self._title.hide()
        self._full_screen.hide()
        self._preview.hide()
        self._description.hide()
        if hasattr(self, '_thumbs'):
            for thumbnail in self._thumbs:
                thumbnail[0].hide()
        self.invalt(0, 0, self._width, self._height)

        # Reset drag settings
        self._press = None
        self._release = None
        self._dragpos = [0, 0]
        self._total_drag = [0, 0]
        self.last_spr_moved = None

    def _show_slide(self):
        ''' Display a title, preview image, and decription for slide i. '''
        self._clear_screen()

        if self._nobjects == 0:
            self._prev_button.set_icon('go-previous-inactive')
            self._next_button.set_icon('go-next-inactive')
            self._description.set_label(
                _('Do you have any items in your Journal starred?'))
            self._description.set_layer(MIDDLE)
            return

        if self.i == 0:
            self._prev_button.set_icon('go-previous-inactive')
        else:
            self._prev_button.set_icon('go-previous')
        if self.i == self._nobjects - 1:
            self._next_button.set_icon('go-next-inactive')
        else:
            self._next_button.set_icon('go-next')

        pixbuf = None
        media_object = False
        try:
            pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                self._dsobjects[self.i].file_path, int(PREVIEWW * self._scale),
                int(PREVIEWH * self._scale))
            media_object = True
        except:
            pixbuf = get_pixbuf_from_journal(self._dsobjects[self.i], 300, 225)

        if pixbuf is not None:
            if not media_object:
                self._preview.images[0] = pixbuf.scale_simple(
                    int(PREVIEWW * self._scale), int(PREVIEWH * self._scale),
                    gtk.gdk.INTERP_TILES)
                self._full_screen.hide()
                self._preview.set_layer(MIDDLE)
            else:
                self._full_screen.images[0] = pixbuf.scale_simple(
                    int(FULLW * self._scale), int(FULLH * self._scale),
                    gtk.gdk.INTERP_TILES)
                self._full_screen.set_layer(MIDDLE)
                self._preview.hide()
        else:
            if self._preview is not None:
                self._preview.hide()
                self._full_screen.hide()

        self._title.set_label(self._dsobjects[self.i].metadata['title'])
        self._title.set_layer(MIDDLE)

        if 'description' in self._dsobjects[self.i].metadata:
            if media_object:
                self._description2.set_label(
                    self._dsobjects[self.i].metadata['description'])
                self._description2.set_layer(MIDDLE)
                self._description.set_label('')
                self._description.hide()
            else:
                self._description.set_label(
                    self._dsobjects[self.i].metadata['description'])
                self._description.set_layer(MIDDLE)
                self._description2.set_label('')
                self._description2.hide()
        else:
            self._description.set_label('')
            self._description.hide()
            self._description2.set_label('')
            self._description2.hide()
        if self._hw == XO175:
            self._bump_id = gobject.timeout_add(int(500), self._bump_test)

    def _thumbs_cb(self, button=None):
        ''' Toggle between thumbnail view and slideshow view. '''
        if self._thumbnail_mode:
            self._set_view_mode(self._current_slide)
            self._show_slide()
        else:
            self._stop_autoplay()
            self._current_slide = self.i
            self._thumbnail_mode = True
            self._clear_screen()

            self._prev_button.set_icon('go-previous-inactive')
            self._next_button.set_icon('go-next-inactive')
            self._thumb_button.set_icon('slide-view')
            self._thumb_button.set_tooltip(_('Slide view'))

            n = int(sqrt(self._nobjects) + 0.5)
            w = int(self._width / n)
            h = int(w * 0.75)  # maintain 4:3 aspect ratio
            x_off = int((self._width - n * w) / 2)
            x = x_off
            y = 0
            for i in range(self._nobjects):
                self.i = i
                self._show_thumb(x, y, w, h)
                x += w
                if x + w > self._width:
                    x = x_off
                    y += h
            self.i = 0  # Reset position in slideshow to the beginning
        return False

    def _show_thumb(self, x, y, w, h):
        ''' Display a preview image and title as a thumbnail. '''

        if len(self._thumbs) < self.i + 1:
            # Create a Sprite for this thumbnail
            pixbuf = None
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                    self._dsobjects[self.i].file_path, int(w), int(h))
            except:
                pixbuf = get_pixbuf_from_journal(self._dsobjects[self.i],
                                                 int(w), int(h))
            pixbuf_thumb = pixbuf.scale_simple(int(w), int(h),
                                               gtk.gdk.INTERP_TILES)

            self._thumbs.append(
                [Sprite(self._sprites, x, y, pixbuf_thumb), x, y, self.i])
            self._thumbs[-1][0].set_label(str(self.i + 1))
        self._thumbs[self.i][0].set_layer(TOP)

    def do_fullscreen_cb(self, button):
        ''' Hide the Sugar toolbars. '''
        self.fullscreen()

    def invalt(self, x, y, w, h):
        ''' Mark a region for refresh '''
        self._canvas.window.invalidate_rect(
            gtk.gdk.Rectangle(int(x), int(y), int(w), int(h)), False)

    def _spr_to_thumb(self, spr):
        ''' Find which entry in the thumbnails table matches spr. '''
        for i, thumb in enumerate(self._thumbs):
            if spr == thumb[0]:
                return i
        return -1

    def _spr_is_thumbnail(self, spr):
        ''' Does spr match an entry in the thumbnails table? '''
        if self._spr_to_thumb(spr) == -1:
            return False
        else:
            return True

    def _button_press_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a thumbnail sprite? '''
        win.grab_focus()
        x, y = map(int, event.get_coords())

        self._dragpos = [x, y]
        self._total_drag = [0, 0]

        spr = self._sprites.find_sprite((x, y))
        self._press = None
        self._release = None

        # Are we clicking on a thumbnail?
        if not self._spr_is_thumbnail(spr):
            return False

        _logger.debug('found a thumbnail')
        self.last_spr_moved = spr
        self._press = spr
        self._press.set_layer(DRAG)
        return False

    def _mouse_move_cb(self, win, event):
        """ Drag a thumbnail with the mouse. """
        spr = self._press
        if spr is None:
            self._dragpos = [0, 0]
            return False
        win.grab_focus()
        x, y = map(int, event.get_coords())
        dx = x - self._dragpos[0]
        dy = y - self._dragpos[1]
        spr.move_relative([dx, dy])
        self._dragpos = [x, y]
        self._total_drag[0] += dx
        self._total_drag[1] += dy
        return False

    def _button_release_cb(self, win, event):
        ''' Button event is used to swap slides or goto next slide. '''
        win.grab_focus()
        self._dragpos = [0, 0]
        x, y = map(int, event.get_coords())

        if self._thumbnail_mode:
            # Drop the dragged thumbnail below the other thumbnails so
            # that you can find the thumbnail beneath it.
            self._press.set_layer(UNDRAG)
            i = self._spr_to_thumb(self._press)
            spr = self._sprites.find_sprite((x, y))
            if self._spr_is_thumbnail(spr):
                self._release = spr
                # If we found a thumbnail and it is not the one we
                # dragged, swap their positions.
                if not self._press == self._release:
                    j = self._spr_to_thumb(self._release)
                    self._thumbs[i][0] = self._release
                    self._thumbs[j][0] = self._press
                    tmp = self._dsobjects[i]
                    self._dsobjects[i] = self._dsobjects[j]
                    self._dsobjects[j] = tmp
                    self._thumbs[j][0].move(
                        (self._thumbs[j][1], self._thumbs[j][2]))
            self._thumbs[i][0].move((self._thumbs[i][1], self._thumbs[i][2]))
            self._press.set_layer(TOP)
            self._press = None
            self._release = None
        else:
            self._next_cb()
        return False

    def _set_view_mode(self, i):
        ''' Switch to slide-viewing mode. '''
        self._thumbnail_mode = False
        self.i = i
        self._thumb_button.set_icon('thumbs-view')
        self._thumb_button.set_tooltip(_('Thumbnail view'))

    def _unit_combo_cb(self, arg=None):
        ''' Read value of predefined conversion factors from combo box '''
        if hasattr(self, '_unit_combo'):
            active = self._unit_combo.get_active()
            if active in UNIT_DICTIONARY:
                self._rate = UNIT_DICTIONARY[active][1]
Beispiel #24
0
class Turtle:

    def __init__(self, turtles, key, turtle_colors=None):
        """ The turtle is not a block, just a sprite with an orientation """
        self.x = 0
        self.y = 0
        self.hidden = False
        self.shapes = []
        self.custom_shapes = False
        self.type = 'turtle'
        self.heading = 0
        self.pen_shade = 50
        self.pen_color = 0
        self.pen_gray = 100
        self.pen_size = 5
        self.pen_state = True

        # If the turtle key is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(key)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (color_table[fill]),
                           '#%06x' % (color_table[stroke])]
            self.shapes = generate_turtle_pixbufs(self.colors)
        else:
            self.shapes = turtles.get_pixbufs()

        if turtles.sprite_list is not None:
            self.spr = Sprite(turtles.sprite_list, 0, 0, self.shapes[0])
        else:
            self.spr = None
        turtles.add_to_dict(key, self)

    def set_shapes(self, shapes):
        """ Reskin the turtle """
        n = len(shapes)
        if n == SHAPES:
            self.shapes = shapes[:]
        else:
            if n != 1:
                _logger.debug("%d images passed to set_shapes: ignoring" % (n))
            images = [shapes[0]]
            if self.heading == 0:
                for i in range(3):
                    images.append(images[i].rotate_simple(270))
                for i in range(SHAPES):
                    j = (i + 4) % SHAPES
                    self.shapes[j] = images[int(j / 9)]
            else:
                j = int(self.heading + 5) % 360 / (360 / SHAPES)
                self.shapes[j] = images[0]
        self.custom_shapes = True
        self.show()

    def reset_shapes(self):
        """ Reset the shapes to the standard turtle """
        if self.custom_shapes:
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.custom_shapes = False

    def set_heading(self, heading):
        """ Set the turtle heading (one shape per 360/SHAPES degrees) """
        self.heading = heading
        i = (int(self.heading + 5) % 360) / (360 / SHAPES)
        if not self.hidden and self.spr is not None:
            try:
                self.spr.set_shape(self.shapes[i])
            except IndexError:
                self.spr.set_shape(self.shapes[0])

    def set_color(self, color):
        """ Set the pen color for this turtle. """
        self.pen_color = color

    def set_gray(self, gray):
        """ Set the pen gray level for this turtle. """
        self.pen_gray = gray

    def set_shade(self, shade):
        """ Set the pen shade for this turtle. """
        self.pen_shade = shade

    def set_pen_size(self, pen_size):
        """ Set the pen size for this turtle. """
        self.pen_size = pen_size

    def set_pen_state(self, pen_state):
        """ Set the pen state (down==True) for this turtle. """
        self.pen_state = pen_state

    def hide(self):
        """ Hide the turtle. """
        if self.spr is not None:
            self.spr.hide()
        self.hidden = True

    def show(self):
        """ Show the turtle. """
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self.hidden = False
        self.move((self.x, self.y))
        self.set_heading(self.heading)

    def move(self, pos):
        """ Move the turtle. """
        self.x, self.y = int(pos[0]), int(pos[1])
        if not self.hidden and self.spr is not None:
            self.spr.move(pos)
        return(self.x, self.y)

    def get_xy(self):
        """ Return the turtle's x, y coordinates. """
        return(self.x, self.y)

    def get_heading(self):
        """ Return the turtle's heading. """
        return(self.heading)

    def get_color(self):
        """ Return the turtle's color. """
        return(self.pen_color)

    def get_gray(self):
        """ Return the turtle's gray level. """
        return(self.pen_gray)

    def get_shade(self):
        """ Return the turtle's shade. """
        return(self.pen_shade)

    def get_pen_size(self):
        """ Return the turtle's pen size. """
        return(self.pen_size)

    def get_pen_state(self):
        """ Return the turtle's pen state. """
        return(self.pen_state)
Beispiel #25
0
class Game():

    def __init__(self, canvas, parent=None, colors=['#A0FFA0', '#FF8080']):
        self._activity = parent
        self._colors = [colors[0]]
        self._colors.append(colors[1])
        self._colors.append('#FFFFFF')
        self._colors.append('#000000')
        self._colors.append('#FF0000')
        self._colors.append('#FF8000')
        self._colors.append('#FFFF00')
        self._colors.append('#00FF00')
        self._colors.append('#00FFFF')
        self._colors.append('#0000FF')
        self._colors.append('#FF00FF')

        self._canvas = canvas
        if parent is not None:
            parent.show_all()
            self._parent = parent

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)
        self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.connect("button-release-event", self._button_release_cb)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)
        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - GRID_CELL_SIZE

        scale = [self._width / (10 * DOT_SIZE * 1.2),
                 self._height / (6 * DOT_SIZE * 1.2)]
        self._scale = min(scale)

        self._dot_size = int(DOT_SIZE * self._scale)
        self._space = int(self._dot_size / 5.)
        self._orientation = 'horizontal'
        self.we_are_sharing = False
        self.playing_with_robot = False
        self._press = False
        self.last_spr = None
        self._timer = None
        self.roygbiv = False

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._dots = []
        for y in range(SIX):
            for x in range(TEN):
                xoffset = int((self._width - TEN * self._dot_size - \
                                   (TEN - 1) * self._space) / 2.)
                self._dots.append(
                    Sprite(self._sprites,
                           xoffset + x * (self._dot_size + self._space),
                           y * (self._dot_size + self._space),
                           self._new_dot(self._colors[2])))
                self._dots[-1].type = 2  # not set
                self._dots[-1].set_label_attributes(40)

        self.vline = Sprite(self._sprites,
                            int(self._width / 2.) - 1,
                            0, self._line(vertical=True))
        n = SIX / 2.
        self.hline = Sprite(
            self._sprites, 0,
            int(self._dot_size * n + self._space * (n - 0.5)) - 1,
            self._line(vertical=False))
        self.hline.hide()

        # and initialize a few variables we'll need.
        self._all_clear()

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        for dot in self._dots:
            dot.type = 2
            dot.set_shape(self._new_dot(self._colors[2]))
            dot.set_label('')

        self._set_orientation()

    def _set_orientation(self):
        ''' Set bar and message for current orientation '''
        if self._orientation == 'horizontal':
            self.hline.hide()
            self.vline.set_layer(1000)
        elif self._orientation == 'vertical':
            self.hline.set_layer(1000)
            self.vline.hide()
        else:
            self.hline.set_layer(1000)
            self.vline.set_layer(1000)

        '''
        if self._orientation == 'horizontal':
            self._set_label(
                _('Click on the dots to make a horizontal reflection.'))
        elif self._orientation == 'vertical':
            self._set_label(
                _('Click on the dots to make a vertical reflection.'))
        else:
            self._set_label(
                _('Click on the dots to make a bilateral reflection.'))
        '''

    def _initiating(self):
        return self._activity.initiating

    def new_game(self, orientation='horizontal'):
        ''' Start a new game. '''
        self._orientation = orientation

        self._all_clear()

        # Fill in a few dots to start
        for i in range(int(TEN * SIX / 2)):
            n = int(uniform(0, TEN * SIX))
            if self.roygbiv:
                self._dots[n].type = int(uniform(2, len(self._colors)))
            else:
                self._dots[n].type = int(uniform(0, 4))
            self._dots[n].set_shape(self._new_dot(
                    self._colors[self._dots[n].type]))

        if self.we_are_sharing:
            _logger.debug('sending a new game')
            self._parent.send_new_game()

    def restore_game(self, dot_list, orientation):
        ''' Restore a game from the Journal or share '''
        for i, dot in enumerate(dot_list):
            self._dots[i].type = dot
            self._dots[i].set_shape(self._new_dot(
                    self._colors[self._dots[i].type]))
        self._orientation = orientation
        self._set_orientation()

    def save_game(self):
        ''' Return dot list and orientation for saving to Journal or
        sharing '''
        dot_list = []
        for dot in self._dots:
            dot_list.append(dot.type)
        return [dot_list, self._orientation]

    def _set_label(self, string):
        ''' Set the label in the toolbar or the window frame. '''
        self._activity.status.set_label(string)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = map(int, event.get_coords())
        self._press = True

        spr = self._sprites.find_sprite((x, y))
        if spr == None:
            return True

        self.last_spr = spr
        if spr.type is not None:
            if not self._timer is None:
                GObject.source_remove(self._timer)
            self._increment_dot(spr)
        return True

    def _button_release_cb(self, win, event):
        self._press = False
        if not self._timer is None:
            GObject.source_remove(self._timer)

    def _increment_dot(self, spr):
        spr.type += 1
        if self.roygbiv:
            if spr.type >= len(self._colors):
                spr.type = 2
        else:
            spr.type %= 4
        spr.set_shape(self._new_dot(self._colors[spr.type]))

        if self.playing_with_robot:
            self._robot_play(spr)

        self._test_game_over()

        if self.we_are_sharing:
            _logger.debug('sending a click to the share')
            self._parent.send_dot_click(self._dots.index(spr), spr.type)

        self._timer = GObject.timeout_add(1000, self._increment_dot, spr)

    def _mouse_move_cb(self, win, event):
        """ Drag a tile with the mouse. """
        if not self._press:
            return
        x, y = map(int, event.get_coords())
        spr = self._sprites.find_sprite((x, y))
        if spr == self.last_spr:
            return True
        if spr is None:
            return True
        if spr.type is not None:
            self.last_spr = spr
            if not self._timer is None:
                GObject.source_remove(self._timer)
            self._increment_dot(spr)

    def _robot_play(self, dot):
        ''' Robot reflects dot clicked. '''
        x, y = self._dot_to_grid(self._dots.index(dot))
        if self._orientation == 'horizontal':
            x = TEN - x - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
        elif self._orientation == 'vertical':
            y = SIX - y - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
        else:
            x = TEN - x - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
            y = SIX - y - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)
            x = TEN - x - 1
            i = self._grid_to_dot((x, y))
            self._dots[i].type = dot.type
            self._dots[i].set_shape(self._new_dot(self._colors[dot.type]))
            if self.we_are_sharing:
                _logger.debug('sending a robot click to the share')
                self._parent.send_dot_click(i, dot.type)

    def remote_button_press(self, dot, color):
        ''' Receive a button press from a sharer '''
        self._dots[dot].type = color
        self._dots[dot].set_shape(self._new_dot(self._colors[color]))

    def set_sharing(self, share=True):
        _logger.debug('enabling sharing')
        self.we_are_sharing = share

    def _smile(self):
        for dot in self._dots:
            dot.set_label(':)')

    def _test_game_over(self):
        ''' Check to see if game is over '''
        if self._orientation == 'horizontal':
            for y in range(SIX):
                for x in range(SIX):
                    if self._dots[y * TEN + x].type != \
                            self._dots[y * TEN + TEN - x - 1].type:
                        self._set_label(_('keep trying'))
                        return False
            self._set_label(_('good work'))
            self._smile()
            return True
        if self._orientation == 'vertical':
            for y in range(int(SIX / 2)):
                for x in range(TEN):
                    if self._dots[y * TEN + x].type != \
                            self._dots[(SIX - y - 1) * TEN + x].type:
                        self._set_label(_('keep trying'))
                        return False
            self._set_label(_('good work'))
        else:
            for y in range(SIX):
                for x in range(SIX):
                    if self._dots[y * TEN + x].type != \
                            self._dots[y * TEN + TEN - x - 1].type:
                        self._set_label(_('keep trying'))
                        return False
            for y in range(int(SIX / 2)):
                for x in range(TEN):
                    if self._dots[y * TEN + x].type != \
                            self._dots[(SIX - y - 1) * TEN + x].type:
                        self._set_label(_('keep trying'))
                        return False
            self._set_label(_('good work'))
        self._smile()
        return True
    def __draw_cb(self,canvas,cr):
		self._sprites.redraw_sprites(cr=cr)
    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * TEN

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % TEN, int(dot / TEN)]

    def _expose_cb(self, win, event):
        self.do_expose_event(event)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()

    def _new_dot(self, color):
        ''' generate a dot of a color color '''
        self._dot_cache = {}
        if not color in self._dot_cache:
            self._stroke = color
            self._fill = color
            self._svg_width = self._dot_size
            self._svg_height = self._dot_size
            pixbuf = svg_str_to_pixbuf(
                self._header() + \
                self._circle(self._dot_size / 2., self._dot_size / 2.,
                             self._dot_size / 2.) + \
                self._footer())

            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                         self._svg_width, self._svg_height)
            context = cairo.Context(surface)
            Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
            context.rectangle(0, 0, self._svg_width, self._svg_height)
            context.fill()
            self._dot_cache[color] = surface

        return self._dot_cache[color]

    def _line(self, vertical=True):
        ''' Generate a center line '''
        if vertical:
            self._svg_width = 3
            self._svg_height = self._height
            return svg_str_to_pixbuf(
                self._header() + \
                self._rect(3, self._height, 0, 0) + \
                self._footer())
        else:
            self._svg_width = self._width
            self._svg_height = 3
            return svg_str_to_pixbuf(
                self._header() + \
                self._rect(self._width, 3, 0, 0) + \
                self._footer())

    def _header(self):
        return '<svg\n' + 'xmlns:svg="http://www.w3.org/2000/svg"\n' + \
            'xmlns="http://www.w3.org/2000/svg"\n' + \
            'xmlns:xlink="http://www.w3.org/1999/xlink"\n' + \
            'version="1.1"\n' + 'width="' + str(self._svg_width) + '"\n' + \
            'height="' + str(self._svg_height) + '">\n'

    def _rect(self, w, h, x, y):
        svg_string = '       <rect\n'
        svg_string += '          width="%f"\n' % (w)
        svg_string += '          height="%f"\n' % (h)
        svg_string += '          rx="%f"\n' % (0)
        svg_string += '          ry="%f"\n' % (0)
        svg_string += '          x="%f"\n' % (x)
        svg_string += '          y="%f"\n' % (y)
        svg_string += 'style="fill:#000000;stroke:#000000;"/>\n'
        return svg_string

    def _circle(self, r, cx, cy):
        return '<circle style="fill:' + str(self._fill) + ';stroke:' + \
            str(self._stroke) + ';" r="' + str(r - 0.5) + '" cx="' + \
            str(cx) + '" cy="' + str(cy) + '" />\n'

    def _footer(self):
        return '</svg>\n'
Beispiel #26
0
class Game():
    def __init__(self, canvas, parent=None, path=None):
        self._canvas = canvas
        self._parent = parent
        self._parent.show_all()
        self._path = path

        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)
        self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)
        self._canvas.connect('button-release-event', self._button_release_cb)
        self._canvas.add_events(Gdk.EventMask.KEY_PRESS_MASK)
        self._canvas.connect('key-press-event', self._keypress_cb)

        self._canvas.set_can_focus(True)
        self._canvas.grab_focus()

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height()
        self._scale_x = self._width / 1200.0
        self._scale_y = self._height / 900.0
        self._first_time = True
        self._loco_pos = (0, 0)
        self._loco_dim = (0, 0)
        self._loco_quadrant = 3
        self._drag_pos = [0, 0]
        self._counter = 0
        self._correct = 0
        self._timeout_id = None
        self._pause = 200
        self._press = None
        self._clicked = False
        self._dead_key = None
        self._waiting_for_delete = False
        self._waiting_for_enter = False
        self._seconds = 0
        self._timer_id = None
        self.level = 0
        self.score = 0

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        self._BG = [
            'background0.jpg', 'background0.jpg', 'background0.jpg',
            'background1.jpg', 'background2.jpg', 'background2.jpg',
            'background2.jpg'
        ]
        self._backgrounds = []
        for bg in self._BG:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file(
                os.path.join(self._path, 'images', bg))
            pixbuf = pixbuf.scale_simple(self._width, self._height,
                                         GdkPixbuf.InterpType.BILINEAR)
            self._backgrounds.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._backgrounds[-1].type = 'background'
            self._backgrounds[-1].hide()

        self._panel = Sprite(
            self._sprites, int(400 * self._scale_x), int(400 * self._scale_y),
            GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(self._path, 'images', 'ventana.png'),
                int(720 * self._scale_x), int(370 * self._scale_y)))
        self._panel.type = 'panel'
        self._panel.set_label(LABELS[0])
        self._panel.set_label_attributes(20)
        self._panel.hide()

        self._LOCOS = glob.glob(os.path.join(self._path, 'images',
                                             'loco*.png'))
        self._loco_cards = []
        for loco in self._LOCOS:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale_x), int(208 * self._scale_y))
            self._loco_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._loco_cards[-1].type = 'loco'
        self._loco_dim = (int(150 * self._scale_x), int(208 * self._scale_y))

        self._MEN = glob.glob(os.path.join(self._path, 'images', 'man*.png'))
        self._man_cards = []
        for loco in self._MEN:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale_x), int(208 * self._scale_y))
            self._man_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._man_cards[-1].type = 'loco'

        self._TAUNTS = glob.glob(
            os.path.join(self._path, 'images', 'taunt*.png'))
        self._taunt_cards = []
        for loco in self._TAUNTS:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale_x), int(208 * self._scale_y))
            self._taunt_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._taunt_cards[-1].type = 'loco'

        self._GHOSTS = glob.glob(
            os.path.join(self._path, 'images', 'ghost*.png'))
        self._ghost_cards = []
        for loco in self._GHOSTS:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                loco, int(150 * self._scale_x), int(208 * self._scale_y))
            self._ghost_cards.append(Sprite(self._sprites, 0, 0, pixbuf))
            self._ghost_cards[-1].type = 'loco'

        self._sticky_cards = []
        self._loco_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            self._LOCOS[0], int(150 * self._scale_x), int(208 * self._scale_y))
        self._man_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            self._MEN[0], int(150 * self._scale_x), int(208 * self._scale_y))
        self._ghost_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            self._GHOSTS[0], int(150 * self._scale_x),
            int(208 * self._scale_y))
        for i in range(len(MSGS[1])):  # Check re i18n
            self._sticky_cards.append(
                Sprite(self._sprites, 0, 0, self._loco_pixbuf))
            self._sticky_cards[-1].type = 'loco'
            self._sticky_cards[-1].set_label_attributes(24,
                                                        vert_align='bottom')

        self._all_clear()

    def _time_increment(self):
        ''' Track seconds since start_time. '''
        self._seconds = int(GLib.get_current_time() - self._start_time)
        self.timer_id = GLib.timeout_add(1000, self._time_increment)

    def _timer_reset(self):
        ''' Reset the timer for each level '''
        self._start_time = GLib.get_current_time()
        if self._timer_id is not None:
            GLib.source_remove(self._timer_id)
            self._timer_id = None
        self.score += self._seconds
        self._time_increment()

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        for p in self._loco_cards:
            p.hide()
        for p in self._man_cards:
            p.hide()
        for p in self._taunt_cards:
            p.hide()
        for p in self._ghost_cards:
            p.hide()
        for p in self._sticky_cards:
            p.set_shape(self._loco_pixbuf)
            p.set_label('')
            p.set_label_color('white')
            p.hide()
        self._backgrounds[self.level].set_layer(BG_LAYER)

    def _show_time(self):
        self.level = 0
        self._all_clear()
        x = int(self._width / 4.)
        y = int(self._height / 8.)
        for i in range(len(str(self.score))):
            self._sticky_cards[i].move((x, y))
            self._sticky_cards[i].set_layer(LOCO_LAYER)
            self._sticky_cards[i].set_label(str(self.score)[i])
            x += int(self._loco_dim[0] / 2.)
        self.score = 0
        self._parent.fullscreen()
        aplay.play(os.path.join(self._path, 'sounds', 'sonar.ogg'))
        GLib.timeout_add(5000, self.new_game, True)

    def new_game(self, first_time):
        ''' Start a new game at the current level. '''
        self._first_time = first_time
        self._clicked = False

        # It may be time to advance to the next level.
        if (self.level == 6 and self._counter == len(MSGS)) or \
           self._counter > 4:
            self._first_time = True
            self.level += 1
            self._counter = 0
            self._correct = 0
            self._pause = 200
            if self.level == len(self._backgrounds):
                self._show_time()
                return

        self._all_clear()

        if self._first_time:
            # Every game starts by putting up a panel with instructions
            # The panel disappears on mouse movement
            self._panel.set_label(LABELS[self.level])
            self._panel.set_layer(PANEL_LAYER)
            aplay.play(os.path.join(self._path, 'sounds', 'drip.ogg'))
            self._timer_reset()

        if self.level == 0:
            # Choose a random location for the Loco
            self._loco_quadrant += int(uniform(1, 4))
            self._loco_quadrant %= 4
            x, y = self._quad_to_xy(self._loco_quadrant)
            aplay.play(os.path.join(self._path, 'sounds', 'bark.ogg'))
            self._loco_cards[0].move((x, y))
            self._loco_pos = (x, y)
        elif self.level == 1:
            aplay.play(os.path.join(self._path, 'sounds', 'glass.ogg'))
        elif self.level == 2:
            aplay.play(os.path.join(self._path, 'sounds', 'glass.ogg'))
            # Place some Locos on the canvas
            for i in range(self._counter + 1):
                self._loco_quadrant += int(uniform(1, 4))
                self._loco_quadrant %= 4
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
        elif self.level == 3:
            aplay.play(os.path.join(self._path, 'sounds', 'bark.ogg'))
            # Place some Locos on the left-side of the canvas
            for i in range(self._counter + 1):
                self._loco_quadrant = int(uniform(2, 4))
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
        elif self.level == 4:
            # Place some Locos on the canvas with letters as labels
            # Just lowercase
            for i in range(self._counter + 1):
                self._loco_quadrant = int(uniform(0, 4))
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
                self._sticky_cards[i].set_label(ALPHABETLC[int(
                    uniform(0, len(ALPHABETLC)))])
        elif self.level == 5:
            # Place some Locos on the canvas with letters as labels
            # Uppercase
            for i in range(self._counter + 1):
                self._loco_quadrant = int(uniform(0, 4))
                x, y = self._quad_to_xy(self._loco_quadrant)
                self._sticky_cards[i].move((x, y))
                self._sticky_cards[i].type = 'loco'
                self._sticky_cards[i].set_layer(LOCO_LAYER)
                self._sticky_cards[i].set_label(ALPHABETUC[int(
                    uniform(0, len(ALPHABETUC)))])
        elif self.level == 6:
            x = 0
            y = 0
            c = 0
            for i in range(len(MSGS[self._counter])):
                if MSGS[self._counter][i] == ' ':
                    y += self._loco_dim[1]
                    x = 0
                else:
                    self._sticky_cards[c].move((x, y))
                    self._sticky_cards[c].type = i
                    self._sticky_cards[c].set_layer(LOCO_LAYER)
                    self._sticky_cards[c].set_label(MSGS[self._counter][i])
                    c += 1
                    x += int(self._loco_dim[0] / 2.)

        if self.level in [0, 1]:
            self._loco_quadrant += int(uniform(1, 4))
            self._loco_quadrant %= 4
            x, y = self._quad_to_xy(self._loco_quadrant)
            if self.level == 0:
                self._move_loco(x, y, 0)
            else:
                self._taunt(x, y, 0)

    def _quad_to_xy(self, q):
        x = int(max(0, (self._width / 2.) * uniform(0, 1) - self._loco_dim[0]))
        if q in [0, 1]:
            x += int(self._width / 2.)
        y = int(max(0,
                    (self._height / 2.) * uniform(0, 1) - self._loco_dim[1]))
        if q in [1, 2]:
            y += int(self._height / 2.)
        return x, y

    def _taunt(self, x, y, i):
        n = len(self._taunt_cards)
        self._taunt_cards[(i + 1) % n].hide()
        if self._clicked:
            self._timeout_id = None
            return True
        else:
            self._taunt_cards[i % n].move((x, y))
            self._taunt_cards[i % n].set_layer(LOCO_LAYER)
            self._timeout_id = GLib.timeout_add(200, self._taunt, x, y, i + 1)

    def _move_loco(self, x, y, i):
        j = (i + 1) % len(self._loco_cards)
        cx, cy = self._loco_cards[i].get_xy()
        dx = cx - x
        dy = cy - y
        if dx * dx + dy * dy < 100:
            self._loco_cards[j].move((x, y))
            self._loco_pos = (x, y)
            self._loco_cards[j].hide()
            self._loco_cards[i].hide()
            self._man_cards[0].move((x, y))
            self._man_cards[0].set_layer(LOCO_LAYER)
            self._timeout_id = None
            if self._pause > 50:
                self._pause -= 10
            return True
        else:
            if dx > 0:
                cx -= 5
            elif dx < 0:
                cx += 5
            if dy > 0:
                cy -= 5
            elif dy < 0:
                cy += 5
            self._loco_cards[j].move((cx, cy))
            self._loco_pos = (cx, cy)
            self._loco_cards[j].set_layer(LOCO_LAYER)
            self._loco_cards[i].hide()
            self._timeout_id = GLib.timeout_add(self._pause, self._move_loco,
                                                x, y, j)

    def _keypress_cb(self, area, event):
        ''' Keypress '''
        # Games 4, 5, and 6 use the keyboard
        if self.level not in [4, 5, 6]:
            return True
        k = Gdk.keyval_name(event.keyval)

        if self._waiting_for_enter:
            if k == 'Return':
                self._waiting_for_enter = False
                self._panel.hide()
                self._counter += 1
                self._correct = 0
                GLib.timeout_add(1000, self.new_game, False)
            return

        if k in NOISE_KEYS or k in WHITE_SPACE:
            return True

        if self.level == 6 and self._waiting_for_delete:
            if k in ['BackSpace', 'Delete']:
                self._waiting_for_delete = False
                self._sticky_cards[self._correct].set_label_color('white')
                self._sticky_cards[self._correct].set_label(MSGS[
                    self._counter][self._sticky_cards[self._correct].type])
                self._panel.hide()
                self._panel.set_label_color('black')
            return

        if k[0:5] == 'dead_':
            self._dead_key = k[5:]
            return

        if self.level == 6:
            n = len(MSGS[self._counter])
        else:
            n = self._counter + 1

        if self.level == 6:
            i = self._correct
            if self._dead_key is not None:
                k = DEAD_DICTS[DEAD_KEYS.index(self._dead_key)][k]
                self._dead_key = None
            elif k in PUNCTUATION:
                k = PUNCTUATION[k]
            elif k in SPECIAL:
                k = SPECIAL[k]
            elif len(k) > 1:
                return True
            if self._sticky_cards[i].labels[0] == k:
                self._sticky_cards[i].set_label_color('blue')
                self._sticky_cards[i].set_label(k)
                self._correct += 1
            else:
                self._sticky_cards[i].set_label_color('red')
                self._sticky_cards[i].set_label(k)
                self._panel.set_label_color('red')
                self._panel.set_label(ALERTS[1])
                self._panel.set_layer(PANEL_LAYER)
                self._waiting_for_delete = True
                aplay.play(os.path.join(self._path, 'sounds', 'glass.ogg'))
        else:
            for i in range(n):
                if self._sticky_cards[i].labels[0] == k:
                    self._sticky_cards[i].set_label('')
                    self._sticky_cards[i].hide()
                    break

        # Test for end condition
        if self.level == 6 and \
           self._correct == len(MSGS[self._counter]) - \
                            MSGS[self._counter].count(' '):
            c = 0
            for i in range(len(MSGS[self._counter])):
                if MSGS[self._counter][i] == ' ':
                    continue
                elif MSGS[self._counter][i] != self._sticky_cards[c].labels[0]:
                    return True
                c += 1
            self._panel.set_label(ALERTS[0])
            self._panel.set_layer(PANEL_LAYER)
            self._waiting_for_enter = True
            aplay.play(os.path.join(self._path, 'sounds', 'drip.ogg'))
            return
        else:
            for i in range(n):
                if len(self._sticky_cards[i].labels[0]) > 0:
                    return True
        self._counter += 1
        self._correct = 0
        GLib.timeout_add(1000, self.new_game, False)

    def _mouse_move_cb(self, win, event):
        ''' Move the mouse. '''
        # Games 0, 3, 4, and 5 use move events
        x, y = list(map(int, event.get_coords()))
        if self._seconds > 1:
            self._panel.hide()
        if not self._clicked and self.level == 0:
            # For Game 0, see if the mouse is on the Loco
            dx = x - self._loco_pos[0] - self._loco_dim[0] / 2.
            dy = y - self._loco_pos[1] - self._loco_dim[1] / 2.
            if dx * dx + dy * dy < 200:
                self._clicked = True
                if self._timeout_id is not None:
                    GLib.source_remove(self._timeout_id)
                # Play again
                self._all_clear()
                self._man_cards[0].move((x - int(self._loco_dim[0] / 2.),
                                         y - int(self._loco_dim[1] / 2.)))
                self._man_cards[0].set_layer(LOCO_LAYER)
                self._correct += 1
                self._counter += 1
                GLib.timeout_add(1000, self.new_game, False)
        elif self.level in [4, 5]:
            # For Game 4 and 5, we allow dragging
            if self._press is None:
                self._drag_pos = [0, 0]
                return True
            dx = x - self._drag_pos[0]
            dy = y - self._drag_pos[1]
            self._press.move_relative((dx, dy))
            self._drag_pos = [x, y]
        elif self.level == 3:
            # For Game 3, we are dragging
            if self._press is None:
                self._drag_pos = [0, 0]
                return True
            dx = x - self._drag_pos[0]
            dy = y - self._drag_pos[1]
            self._press.move_relative((dx, dy))
            self._drag_pos = [x, y]
            if x > self._width / 2.:
                self._press.set_shape(self._man_pixbuf)
                if self._press.type == 'loco':
                    self._correct += 1
                    self._press.type = 'man'
        return True

    def _button_release_cb(self, win, event):
        # Game 3 uses release
        if self.level == 3:
            # Move to release
            if self._correct == self._counter + 1:
                self._counter += 1
                self._correct = 0
                GLib.timeout_add(2000, self.new_game, False)
        self._press = None
        self._drag_pos = [0, 0]
        return True

    def _button_press_cb(self, win, event):
        self._press = None
        x, y = list(map(int, event.get_coords()))
        if self.level == 0:
            return
        spr = self._sprites.find_sprite((x, y))
        if spr is None:
            return
        if spr.type != 'loco':
            return
        if self.level < 2 and self._timeout_id is None:
            return
        if self._clicked:
            return

        # Games 1, 2, and 3 involve clicks; Games 4 and 5 allow click to drag
        if self.level == 1:
            self._all_clear()
            self._man_cards[0].move((x - int(self._loco_dim[0] / 2.),
                                     y - int(self._loco_dim[1] / 2.)))
            self._man_cards[0].set_layer(LOCO_LAYER)
            self._clicked = True
            self._counter += 1
            self._correct += 1
            if self._timeout_id is not None:
                GLib.source_remove(self._timeout_id)
            GLib.timeout_add(2000, self.new_game, False)
        elif self.level == 2:
            spr.set_shape(self._ghost_pixbuf)
            spr.type = 'ghost'
            if self._correct == self._counter:
                self._counter += 1
                self._correct = 0
                GLib.timeout_add(2000, self.new_game, False)
            else:
                self._correct += 1
        elif self.level in [3, 4, 5]:
            # In Games 4 and 5, dragging is used to remove overlaps
            self._press = spr
            self._drag_pos = [x, y]
        return True

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y, event.area.width,
                     event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()
Beispiel #27
0
class Selector():
    ''' Selector class abstraction  '''

    def __init__(self, turtle_window, n):
        '''This class handles the display of palette selectors (Only relevant
        to GNOME version and very old versions of Sugar).
        '''

        self.shapes = []
        self.spr = None
        self._turtle_window = turtle_window
        self._index = n

        if not n < len(palette_names):
            # Shouldn't happen, but hey...
            debug_output('palette index %d is out of range' % n,
                         self._turtle_window.running_sugar)
            self._name = 'extras'
        else:
            self._name = palette_names[n]

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%soff.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%soff.svg' % (self._name))
                break

        if icon_pathname is not None:
            off_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            off_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrasoff.svg')))
            error_output('Unable to open %soff.svg' % (self._name),
                         self._turtle_window.running_sugar)

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%son.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%son.svg' % (self._name))
                break

        if icon_pathname is not None:
            on_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            on_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrason.svg')))
            error_output('Unable to open %son.svg' % (self._name),
                         self._turtle_window.running_sugar)

        self.shapes.append(off_shape)
        self.shapes.append(on_shape)

        x = int(ICON_SIZE * self._index)
        self.spr = Sprite(self._turtle_window.sprite_list, x, 0, off_shape)
        self.spr.type = 'selector'
        self.spr.name = self._name
        self.set_layer()

    def set_shape(self, i):
        if self.spr is not None and i in [0, 1]:
            self.spr.set_shape(self.shapes[i])

    def set_layer(self, layer=TAB_LAYER):
        if self.spr is not None:
            self.spr.set_layer(layer)

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
Beispiel #28
0
class Game():

    def __init__(self, canvas, parent=None, path=None, root=None, mode='array',
                 colors=['#A0FFA0', '#FF8080']):
        self._canvas = canvas
        self._parent = parent
        self._path = path
        self._root = root
        self._mode = mode
        self.current_image = 0
        self.playing = False
        self._timeout_id = None
        self._prev_mouse_pos = (0, 0)
        self._start_time = 0

        self._colors = ['#FFFFFF']
        self._colors.append(colors[0])
        self._colors.append(colors[1])

        self._canvas.add_events(
            Gdk.EventMask.BUTTON_PRESS_MASK |
            Gdk.EventMask.BUTTON_RELEASE_MASK |
            Gdk.EventMask.BUTTON_MOTION_MASK |
            Gdk.EventMask.POINTER_MOTION_MASK |
            Gdk.EventMask.POINTER_MOTION_HINT_MASK |
            Gdk.EventMask.TOUCH_MASK)

        self._canvas.connect('draw', self.__draw_cb)
        self._canvas.connect('event', self.__event_cb)

        self.configure(move=False)
        self.we_are_sharing = False

        self._start_time = 0
        self._timeout_id = None

        # Find the image files
        self._PATHS = glob.glob(os.path.join(self._path, 'images', '*.svg'))

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        a = max(Gdk.Screen.width(), Gdk.Screen.height())
        b = min(Gdk.Screen.width(), Gdk.Screen.height())
        self._bg_pixbufs = []
        if self._parent.tablet_mode:  # text on top
            # landscape
            self._bg_pixbufs.append(svg_str_to_pixbuf(genhole(
                a, a,
                3 * style.GRID_CELL_SIZE,
                style.DEFAULT_SPACING,
                a - 3 * style.GRID_CELL_SIZE,
                style.GRID_CELL_SIZE * 3 + style.DEFAULT_SPACING)))
            # portrait
            self._bg_pixbufs.append(svg_str_to_pixbuf(genhole(
                a, a,
                3 * style.GRID_CELL_SIZE,
                style.DEFAULT_SPACING,
                b - 3 * style.GRID_CELL_SIZE,
                style.GRID_CELL_SIZE * 3 + style.DEFAULT_SPACING)))
        else:  # text on bottom
            # landscape
            self._bg_pixbufs.append(svg_str_to_pixbuf(genhole(
                a, a,
                3 * style.GRID_CELL_SIZE,
                b - style.GRID_CELL_SIZE * 4 - style.DEFAULT_SPACING,
                a - 3 * style.GRID_CELL_SIZE,
                b - style.GRID_CELL_SIZE - style.DEFAULT_SPACING)))
            # portrait
            self._bg_pixbufs.append(svg_str_to_pixbuf(genhole(
                a, a,
                3 * style.GRID_CELL_SIZE,
                a - style.GRID_CELL_SIZE * 4 - style.DEFAULT_SPACING,
                b - 3 * style.GRID_CELL_SIZE,
                a - style.GRID_CELL_SIZE - style.DEFAULT_SPACING)))

        if Gdk.Screen.width() > Gdk.Screen.height():
            self._bg = Sprite(self._sprites, 0, 0, self._bg_pixbufs[0])
        else:
            self._bg = Sprite(self._sprites, 0, 0, self._bg_pixbufs[1])
        self._bg.set_layer(-2)
        self._bg.type = 'background'

        size = 3 * self._dot_size + 4 * self._space
        x = int((Gdk.Screen.width() - size) / 2.)
        self._dots = []
        self._Dots = []  # larger dots for linear mode
        X = int((Gdk.Screen.width() - self._dot_size * 3) / 2.)
        Y = style.GRID_CELL_SIZE + self._yoff
        if self._parent.tablet_mode:
            yoffset = self._space * 2 + self._yoff
        else:
            yoffset = self._yoff
        for y in range(3):
            for x in range(3):
                xoffset = int((self._width - 3 * self._dot_size -
                               2 * self._space) / 2.)
                self._dots.append(
                    Sprite(self._sprites,
                           xoffset + x * (self._dot_size + self._space),
                           y * (self._dot_size + self._space) + yoffset,
                           self._new_dot_surface(color=self._colors[0])))
                self._dots[-1].type = -1  # No image
                self._dots[-1].set_label_attributes(72)
                self._dots[-1].set_label('?')

                self._Dots.append(
                    Sprite(
                        self._sprites, X, Y,
                        self._new_dot_surface(color=self._colors[0],
                                              large=True)))
                self._Dots[-1].type = -1  # No image
                self._Dots[-1].set_label_attributes(72 * 3)
                self._Dots[-1].set_label('?')

        self.number_of_images = len(self._PATHS)
        if USE_ART4APPS:
            self._art4apps = Art4Apps()
            self.number_of_images = len(self._art4apps.get_words())

        self._record_pixbufs = []
        for icon in ['media-audio', 'media-audio-recording']:
            self._record_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        self._play_pixbufs = []
        for icon in ['play-inactive', 'play']:
            self._play_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        self._speak_pixbufs = []
        for icon in ['speak-inactive', 'speak']:
            self._speak_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        left = style.GRID_CELL_SIZE
        right = Gdk.Screen.width() - 2 * style.GRID_CELL_SIZE
        y0 = style.DEFAULT_SPACING + style.DEFAULT_PADDING
        y1 = y0 + style.GRID_CELL_SIZE
        y2 = y1 + style.GRID_CELL_SIZE
        if not self._parent.tablet_mode:
            dy = Gdk.Screen.height() - 4 * style.GRID_CELL_SIZE - \
                2 * style.DEFAULT_SPACING
            y0 += dy
            y1 += dy
            y2 += dy
        y3 = int((Gdk.Screen.height() - 2 * style.GRID_CELL_SIZE) / 2)

        self._record = Sprite(
            self._sprites, right, y0, self._record_pixbufs[RECORD_OFF])
        self._record.set_layer(1)
        self._record.type = 'record'

        self._play = Sprite(
            self._sprites, right, y1, self._play_pixbufs[PLAY_OFF])
        self._play.set_layer(1)
        self._play.type = 'play-inactive'

        self._speak = Sprite(
            self._sprites, right, y2, self._speak_pixbufs[SPEAK_OFF])
        self._speak.set_layer(1)
        self._speak.type = 'speak-inactive'

        self._next_prev_pixbufs = []
        for icon in ['go-previous', 'go-next', 'go-previous-inactive',
                     'go-next-inactive']:
            self._next_prev_pixbufs.append(
                GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(self._root, 'icons', icon + '.svg'),
                    style.GRID_CELL_SIZE, style.GRID_CELL_SIZE))

        self._prev = Sprite(
            self._sprites, left, y3, self._next_prev_pixbufs[PREV_INACTIVE])
        self._prev.set_layer(1)
        self._prev.type = 'prev'
        if self._mode == 'array':
            self._prev.hide()

        self._next = Sprite(
            self._sprites, right, y3, self._next_prev_pixbufs[NEXT])
        self._next.set_layer(1)
        self._next.type = 'next'
        if self._mode == 'array':
            self._next.hide()

    def configure(self, move=True):
        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - style.GRID_CELL_SIZE
        if not move:
            if self._height < self._width:
                self._scale = self._height / (3 * DOT_SIZE * 1.2)
            else:
                self._scale = self._width / (3 * DOT_SIZE * 1.2)
            self._scale /= 1.5
            self._dot_size = int(DOT_SIZE * self._scale)
            if self._parent.tablet_mode:  # text on top
                self._yoff = style.GRID_CELL_SIZE * 3 + style.DEFAULT_SPACING
            else:
                self._yoff = style.DEFAULT_SPACING
            self._space = int(self._dot_size / 5.)
            return

        left = style.GRID_CELL_SIZE
        right = Gdk.Screen.width() - 2 * style.GRID_CELL_SIZE
        y0 = style.DEFAULT_SPACING + style.DEFAULT_PADDING
        y1 = y0 + style.GRID_CELL_SIZE
        y2 = y1 + style.GRID_CELL_SIZE
        if not self._parent.tablet_mode:
            dy = Gdk.Screen.height() - 4 * style.GRID_CELL_SIZE - \
                2 * style.DEFAULT_SPACING
            y0 += dy
            y1 += dy
            y2 += dy
        y3 = int((Gdk.Screen.height() - 2 * style.GRID_CELL_SIZE) / 2)
        self._record.move((right, y0))
        self._play.move((right, y1))
        self._speak.move((right, y2))
        self._prev.move((left, y3))
        self._next.move((right, y3))

        # Move the dots
        X = int((Gdk.Screen.width() - self._dot_size * 3) / 2.)
        Y = style.GRID_CELL_SIZE + self._yoff
        if self._parent.tablet_mode:
            yoffset = self._space * 2 + self._yoff
        else:
            yoffset = self._yoff
        for y in range(3):
            for x in range(3):
                xoffset = int((self._width - 3 * self._dot_size -
                               2 * self._space) / 2.)
                self._dots[x + y * 3].move(
                    (xoffset + x * (self._dot_size + self._space),
                        y * (self._dot_size + self._space) + yoffset))
                self._Dots[x + y * 3].move((X, Y))

        # switch orientation the bg sprite
        if Gdk.Screen.width() > Gdk.Screen.height():
            self._bg.set_image(self._bg_pixbufs[0])
        else:
            self._bg.set_image(self._bg_pixbufs[1])
        self._bg.set_layer(-2)

    def set_speak_icon_state(self, state):
        if state:
            self._speak.set_image(self._speak_pixbufs[SPEAK_ON])
            self._speak.type = 'speak'
        else:
            self._speak.set_image(self._speak_pixbufs[SPEAK_OFF])
            self._speak.type = 'speak-inactive'
        self._speak.set_layer(1)

    def set_record_icon_state(self, state):
        if state:
            self._record.set_image(self._record_pixbufs[RECORD_ON])
        else:
            self._record.set_image(self._record_pixbufs[RECORD_OFF])
        self._record.set_layer(1)

    def set_play_icon_state(self, state):
        if state:
            self._play.set_image(self._play_pixbufs[PLAY_ON])
            self._play.type = 'play'
        else:
            self._play.set_image(self._play_pixbufs[PLAY_OFF])
            self._play.type = 'play-inactive'
        self._play.set_layer(1)

    def autoplay(self):
        self.set_mode('linear')  # forces current image to 0
        self.playing = True
        self._autonext(next=False)

    def stop(self):
        self.playing = False
        if self._parent.audio_process is not None:
            self._parent.audio_process.terminate()
            self._parent.audio_process = None
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)
            self._timeout_id = None
        self._parent.autoplay_button.set_icon_name('media-playback-start')
        self._parent.autoplay_button.set_tooltip(_('Play'))
        self._parent.array_button.set_sensitive(True)

    def _autonext(self, next=True):
        self._timeout_id = None
        if not self.playing:
            return

        if next:
            self._Dots[self.current_image].hide()
            self.current_image += 1
            self._Dots[self.current_image].set_layer(100)
            if self.current_image == 8:
                self._next.set_image(
                    self._next_prev_pixbufs[NEXT_INACTIVE])
                self._next.set_layer(1)
            self._prev.set_image(self._next_prev_pixbufs[PREV])
            self._prev.set_layer(1)
        self._parent.check_audio_status()
        self._parent.check_text_status()
        GObject.idle_add(self._play_sound)

    def _poll_audio(self):
        if self._parent.audio_process is None:  # Already stopped?
            return

        if self._parent.audio_process.poll() is None:
            GObject.timeout_add(200, self._poll_audio)
        else:
            self._parent.audio_process = None
            self._next_image()

    def _play_sound(self):
        self._start_time = time.time()

        # Either play back a recording or speak the text
        if self._play.type == 'play':
            self._parent.playback_recording_cb()
            self._poll_audio()
        elif self._speak.type == 'speak':
            bounds = self._parent.text_buffer.get_bounds()
            text = self._parent.text_buffer.get_text(
                bounds[0], bounds[1], True)
            speak(text)
            self._next_image()

    def _next_image(self):
        accumulated_time = int(time.time() - self._start_time)
        if accumulated_time < 5:
            pause = 5 - accumulated_time
        else:
            pause = 1
        if self.playing and self.current_image < 8:
            self._timeout_id = GObject.timeout_add(pause * 1000,
                                                   self._autonext)
        else:
            self.stop()

    def __event_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a sprite? or
            there was a gesture. '''

        left = right = False

        if event.type in (Gdk.EventType.TOUCH_BEGIN,
                          Gdk.EventType.TOUCH_CANCEL,
                          Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_PRESS,
                          Gdk.EventType.BUTTON_RELEASE):

            x = int(event.get_coords()[1])
            y = int(event.get_coords()[2])

            if event.type in (Gdk.EventType.TOUCH_BEGIN,
                              Gdk.EventType.BUTTON_PRESS):
                self._prev_mouse_pos = (x, y)
            elif event.type in (Gdk.EventType.TOUCH_END,
                                Gdk.EventType.BUTTON_RELEASE):

                if self._parent.audio_process is not None:
                    self._parent.audio_process.terminate()
                    self._parent.audio_process = None
                    terminated_audio = True
                else:
                    terminated_audio = False

                if self.playing:
                    self.stop()

                new_mouse_pos = (x, y)
                mouse_movement = (new_mouse_pos[0] - self._prev_mouse_pos[0],
                                  new_mouse_pos[1] - self._prev_mouse_pos[1])

                # horizontal gestures only
                if (abs(mouse_movement[0]) / 5) > abs(mouse_movement[1]):
                    if abs(mouse_movement[0]) > abs(mouse_movement[1]):
                        if mouse_movement[0] < 0:
                            right = True
                        else:
                            left = True

        if event.type in (Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_RELEASE):
            spr = self._sprites.find_sprite((x, y))
            if left or right or spr is not None:
                if spr.type in ['record', 'play', 'play-inactive', 'speak',
                                'speak-inactive']:
                    if spr.type == 'record':
                        self._parent.record_cb()
                    elif spr.type == 'play' and not terminated_audio:
                        self._parent.playback_recording_cb()
                    elif spr.type == 'speak':
                        bounds = self._parent.text_buffer.get_bounds()
                        text = self._parent.text_buffer.get_text(
                            bounds[0], bounds[1], True)
                        speak(text)
                    return
                elif self._mode == 'array':
                    return

                self._parent.speak_text_cb()

                if self._parent.recording:
                    self._parent.record_cb()

                if (left or spr.type == 'prev') and self.current_image > 0:
                    self._Dots[self.current_image].hide()
                    self.current_image -= 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 0:
                        self._prev.set_image(
                            self._next_prev_pixbufs[PREV_INACTIVE])
                    self._next.set_image(self._next_prev_pixbufs[NEXT])
                elif (right or spr.type == 'next') and self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                elif spr.type not in ['prev', 'background'] and \
                        self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                self._parent.check_audio_status()
                self._parent.check_text_status()
                self._prev.set_layer(1)
                self._next.set_layer(1)
        return False

    def get_mode(self):
        return self._mode

    def set_mode(self, mode):
        self.current_image = 0
        self._prev.set_image(self._next_prev_pixbufs[PREV_INACTIVE])
        self._next.set_image(self._next_prev_pixbufs[NEXT])
        if mode == 'array':
            self._mode = 'array'
            self._prev.hide()
            self._next.hide()
        else:
            self._mode = 'linear'
            self._prev.set_layer(1)
            self._next.set_layer(1)

        for i in range(9):
            if self._mode == 'array':
                self._dots[i].set_layer(100)
                self._Dots[i].hide()
            else:
                self._dots[i].hide()
                if self.current_image == i:
                    self._Dots[i].set_layer(100)
                else:
                    self._Dots[i].hide()

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)

        self.set_mode(self._mode)

        if self._mode == 'array':
            for dot in self._dots:
                if dot.type != -1:
                    dot.type = -1
                    dot.set_shape(self._new_dot_surface(
                        self._colors[abs(dot.type)]))
                    dot.set_label('?')
        else:
            for dot in self._Dots:
                if dot.type != -1:
                    dot.type = -1
                    dot.set_shape(self._new_dot_surface(
                        self._colors[abs(dot.type)],
                        large=True))
                    dot.set_label('?')
        self._dance_counter = 0
        self._dance_step()

    def _dance_step(self):
        ''' Short animation before loading new game '''
        if self._mode == 'array':
            for dot in self._dots:
                dot.set_shape(self._new_dot_surface(
                    self._colors[int(uniform(0, 3))]))
        else:
            self._Dots[0].set_shape(self._new_dot_surface(
                self._colors[int(uniform(0, 3))],
                large=True))

        self._dance_counter += 1
        if self._dance_counter < 10:
            self._timeout_id = GObject.timeout_add(500, self._dance_step)
        else:
            self._new_images()

    def new_game(self):
        ''' Start a new game. '''
        self._all_clear()

    def _new_images(self):
        ''' Select pictures at random '''
        used_images = [0] * self.number_of_images
        for i in range(9):
            random_selection = int(uniform(0, self.number_of_images))
            while used_images[random_selection] != 0:
                random_selection = int(uniform(0, self.number_of_images))
            used_images[random_selection] = 1
            self._dots[i].set_label('')
            self._dots[i].type = random_selection
            self._dots[i].set_shape(self._new_dot_surface(
                image=self._dots[i].type))

            self._Dots[i].set_label('')
            self._Dots[i].type = self._dots[i].type
            self._Dots[i].set_shape(self._new_dot_surface(
                image=self._Dots[i].type, large=True))

            if self._mode == 'array':
                self._dots[i].set_layer(100)
                self._Dots[i].hide()
            else:
                if self.current_image == i:
                    self._Dots[i].set_layer(100)
                else:
                    self._Dots[i].hide()
                self._dots[i].hide()

        if self.we_are_sharing:
            self._parent.send_new_images()

    def restore_game(self, dot_list):
        ''' Restore a game from the Journal or share '''

        self.set_mode(self._mode)

        for i, dot in enumerate(dot_list):
            self._dots[i].type = dot
            self._dots[i].set_shape(self._new_dot_surface(
                image=self._dots[i].type))
            self._dots[i].set_label('')

            self._Dots[i].type = dot
            self._Dots[i].set_shape(self._new_dot_surface(
                image=self._Dots[i].type, large=True))
            self._Dots[i].set_label('')

            if self._mode == 'array':
                self._dots[i].set_layer(100)
                self._Dots[i].hide()
            else:
                if self.current_image == i:
                    self._Dots[i].set_layer(100)
                else:
                    self._Dots[i].hide()
                self._dots[i].hide()

    def save_game(self):
        ''' Return dot list for saving to Journal or
        sharing '''
        dot_list = []
        for dot in self._dots:
            dot_list.append(dot.type)
        return dot_list

    def set_sharing(self, share=True):
        self.we_are_sharing = share

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * 3

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % 3, int(dot / 3)]

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def __expose_cb(self, win, event):
        ''' Callback to handle window expose events '''
        self.do_expose_event(event)
        return True

    # Handle the expose-event by drawing
    def do_expose_event(self, event):
        # Create the cairo context
        cr = self._canvas.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                     event.area.width, event.area.height)
        cr.clip()

        # Refresh sprite list
        if cr is not None:
            self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()

    def export(self):
        ''' Write dot to cairo surface. '''
        if self._mode == 'array':
            w = h = int(4 * self._space + 3 * self._dot_size)
            png_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
            cr = cairo.Context(png_surface)
            cr.set_source_rgb(192, 192, 192)
            cr.rectangle(0, 0, w, h)
            cr.fill()
            for i in range(9):
                y = self._space + int(i / 3.) * (self._dot_size + self._space)
                x = self._space + (i % 3) * (self._dot_size + self._space)
                cr.save()
                cr.set_source_surface(self._dots[i].images[0], x, y)
                cr.rectangle(x, y, self._dot_size, self._dot_size)
                cr.fill()
                cr.restore()
        else:
            w = h = int(2 * self._space + 3 * self._dot_size)
            png_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
            cr = cairo.Context(png_surface)
            cr.set_source_rgb(192, 192, 192)
            cr.rectangle(0, 0, w, h)
            cr.fill()
            y = self._space
            x = self._space
            cr.save()
            cr.set_source_surface(self._Dots[self.current_image].images[0],
                                  x, y)
            cr.rectangle(x, y, 3 * self._dot_size, 3 * self._dot_size)
            cr.fill()
            cr.restore()

        return png_surface

    def _new_dot_surface(self, color='#000000', image=None, large=False):
        ''' generate a dot of a color color '''

        if large:
            size = self._dot_size * 3
        else:
            size = self._dot_size
        self._svg_width = size
        self._svg_height = size

        if image is None:  # color dot
            self._stroke = color
            self._fill = color
            pixbuf = svg_str_to_pixbuf(
                self._header() +
                self._circle(size / 2., size / 2., size / 2.) +
                self._footer())
        else:
            if USE_ART4APPS:
                word = self._art4apps.get_words()[image]
                try:
                    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                        self._art4apps.get_image_filename(word), size, size)
                except Exception, e:
                    _logger.error('new dot surface %s %s: %s' %
                                  (image, word, e))
                    word = 'zebra'  # default in case image is not found
                    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                        self._art4apps.get_image_filename(word), size, size)
            else:
class Turtle:

    def __init__(self, turtles, turtle_name, turtle_colors=None):
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._heading = 0.0
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(radius * sin(angle)),
                                 int(radius * cos(angle) + width / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(radius * sin(angle) + width / 2.0),
                                 int(radius * cos(angle) + width / 2.0)]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                            (self._half_height * self._half_height)) / 6

    def set_remote(self):
        self._remote = True

    def get_remote(self):
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def set_heading(self, heading, share=True):
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) '''
        try:
            self._heading = heading
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _update_sprite_heading(self):
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        ''' Set the pen color for this turtle. '''
        # Special case for color blocks
        if color is not None and color in COLORDICT:
            self.set_shade(COLORDICT[color][1], share)
            self.set_gray(COLORDICT[color][2], share)
            if COLORDICT[color][0] is not None:
                self.set_color(COLORDICT[color][0], share)
                color = COLORDICT[color][0]
            else:
                color = self._pen_color
        elif color is None:
            color = self._pen_color

        try:
            self._pen_color = color
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            try:
                self._pen_gray = gray
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            try:
                self._pen_shade = shade
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            try:
                self._pen_size = max(0, pen_size)
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates(
                    (p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                        [self._turtles.turtle_window.nick,
                         shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move((pos[0] + self.label_xy[0],
                                       pos[1] + self.label_xy[1]))

    def right(self, degrees, share=True):
        ''' Rotate turtle clockwise '''
        try:
            self._heading += degrees
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _draw_line(self, old, new, pendown):
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(pos1[0], pos1[1],
                                                         pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def forward(self, distance, share=True):
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy()
        try:
            xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
            ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), True)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        old = self.get_xy()
        try:
            if dragging:
                xcor = x
                ycor = y
            else:
                xcor = x * self._turtles.turtle_window.coord_scale
                ycor = y * self._turtles.turtle_window.coord_scale
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(xcor),
                                               round_int(ycor)]]))
            self._turtles.turtle_window.send_event(event)

    def arc(self, a, r, share=True):
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        try:
            if a < 0:
                pos = self.larc(-a, r)
            else:
                pos = self.rarc(a, r)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(r)]]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(('rarc', npos[0], npos[1], r,
                                              (self._heading - 180) * DEGTOR,
                                              (self._heading - 180 + a)
                                              * DEGTOR))

        self.right(a, False)
        return [cx - r * cos(self._heading * DEGTOR),
                cy + r * sin(self._heading * DEGTOR)]

    def larc(self, a, r):
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(('larc', npos[0], npos[1], r,
                                              (self._heading) * DEGTOR,
                                              (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [cx + r * cos(self._heading * DEGTOR),
                cy - r * sin(self._heading * DEGTOR)]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        ''' Draw a pixbuf '''

        self._turtles.turtle_window.canvas.draw_pixbuf(
            pixbuf, a, b, x, y, w, h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(b),
                                               round_int(pos[0]),
                                               round_int(pos[1]),
                                               round_int(w), round_int(h),
                                               round_int(width),
                                               round_int(height),
                                               data]]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [label, round_int(x),
                                               round_int(y), round_int(size),
                                               round_int(w)]]))
            self._turtles.turtle_window.send_event(event)

    def get_name(self):
        return self._name

    def get_xy(self):
        return [self._x, self._y]
    
    def get_x(self):
        return self._x
    
    def get_y(self):
        return self._y

    def get_heading(self):
        return self._heading

    def get_color(self):
        return self._pen_color

    def get_gray(self):
        return self._pen_gray

    def get_shade(self):
        return self._pen_shade

    def get_pen_size(self):
        return self._pen_size

    def get_pen_state(self):
        return self._pen_state

    def get_fill(self):
        return self._pen_fill

    def get_poly_points(self):
        return self._poly_points

    def get_pixel(self):
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
Beispiel #30
0
class Turtle:

    def __init__(self, turtles, key, turtle_colors=None):
        """ The turtle is not a block, just a sprite with an orientation """
        self.x = 0.0
        self.y = 0.0
        self.hidden = False
        self.shapes = []
        self.custom_shapes = False
        self.type = 'turtle'
        self.name = key
        self.heading = 0.0
        self.pen_shade = 50
        self.pen_color = 0
        self.pen_gray = 100
        self.pen_size = 5
        self.pen_state = True
        self.label_block = None

        self._prep_shapes(key, turtles, turtle_colors)

        # Choose a random angle from which to attach the turtle label.
        if turtles.sprite_list is not None:
            self.spr = Sprite(turtles.sprite_list, 0, 0, self.shapes[0])
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            w = self.shapes[0].get_width()
            r = w * 0.67
            # Restrict angle the the sides 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(r * sin(angle)),
                                 int(r * cos(angle) + w / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(r * sin(angle) + w / 2.0),
                                 int(r * cos(angle) + w / 2.0)]
        else:
            self.spr = None
        turtles.add_to_dict(key, self)

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self.shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self.shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self.heading)

    def set_shapes(self, shapes, i=0):
        """ Reskin the turtle """
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self.shapes):
                self.shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self.shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self.tw.running_sugar)
            if self.heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2., nh / 2.)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2., -nh / 2.)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.,
                                              (nh - h) / 2.)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self.shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self.heading + 5) % 360 / (360 / SHAPES)
                self.shapes[j] = shapes[0]
        self.custom_shapes = True
        self.show()

    def reset_shapes(self):
        """ Reset the shapes to the standard turtle """
        if self.custom_shapes:
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.custom_shapes = False

    def set_heading(self, heading):
        """ Set the turtle heading (one shape per 360/SHAPES degrees) """
        self.heading = heading
        i = (int(self.heading + 5) % 360) / (360 / SHAPES)
        if not self.hidden and self.spr is not None:
            try:
                self.spr.set_shape(self.shapes[i])
            except IndexError:
                self.spr.set_shape(self.shapes[0])

    def set_color(self, color):
        """ Set the pen color for this turtle. """
        self.pen_color = color

    def set_gray(self, gray):
        """ Set the pen gray level for this turtle. """
        self.pen_gray = gray

    def set_shade(self, shade):
        """ Set the pen shade for this turtle. """
        self.pen_shade = shade

    def set_pen_size(self, pen_size):
        """ Set the pen size for this turtle. """
        self.pen_size = pen_size

    def set_pen_state(self, pen_state):
        """ Set the pen state (down==True) for this turtle. """
        self.pen_state = pen_state

    def hide(self):
        """ Hide the turtle. """
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self.hidden = True

    def show(self):
        """ Show the turtle. """
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self.hidden = False
        self.move((self.x, self.y))
        self.set_heading(self.heading)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move(self, pos):
        """ Move the turtle. """
        self.x, self.y = pos[0], pos[1]
        if not self.hidden and self.spr is not None:
            self.spr.move((int(pos[0]), int(pos[1])))
        if self.label_block is not None:
            self.label_block.spr.move((int(pos[0] + self.label_xy[0]),
                                       int(pos[1] + self.label_xy[1])))
        return(self.x, self.y)

    def get_name(self):
        ''' return turtle name (key) '''
        return self.name

    def get_xy(self):
        """ Return the turtle's x, y coordinates. """
        return(self.x, self.y)

    def get_heading(self):
        """ Return the turtle's heading. """
        return(self.heading)

    def get_color(self):
        """ Return the turtle's color. """
        return(self.pen_color)

    def get_gray(self):
        """ Return the turtle's gray level. """
        return(self.pen_gray)

    def get_shade(self):
        """ Return the turtle's shade. """
        return(self.pen_shade)

    def get_pen_size(self):
        """ Return the turtle's pen size. """
        return(self.pen_size)

    def get_pen_state(self):
        """ Return the turtle's pen state. """
        return(self.pen_state)