view mamba/widgets/level.py @ 264:2c9cc902928f

Right-click to erase in the level editor.
author Jeremy Thurgood <firxen@gmail.com>
date Thu, 15 Sep 2011 12:09:55 +0200
parents 71911af9d42d
children a061dd62127c
line wrap: on
line source

from pygame.rect import Rect
from pygame.locals import MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION

from mamba.widgets.base import Widget
from mamba.constants import TILE_SIZE


class EditLevelWidget(Widget):
    def __init__(self, level, offset=(0, 0)):
        self.level = level
        level_rect = Rect(offset, level.get_size())
        self.main_tool = None
        self.tool = None
        self.drawing = False
        super(EditLevelWidget, self).__init__(level_rect)

    def draw(self, surface):
        self.level.draw(surface)

    def set_tool(self, new_tool):
        self.main_tool = new_tool
        self.tool = new_tool

    def event(self, event):
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1:  # Left button
                self.tool = self.main_tool
            else:
                self.tool = '.'
            self.drawing = True
            self.update_tile(event.pos)
        elif event.type == MOUSEBUTTONUP:
            self.drawing = False
        elif event.type == MOUSEMOTION and self.drawing:
            # FIXME: Need to consider leaving and re-entering the widget
            self.update_tile(event.pos)

    def update_tile(self, pixel_pos):
        """Update the tile at the current mouse position"""
        # We convert our current position into a tile position
        # and replace the tile with the current tool
        tile_pos = (pixel_pos[0] / TILE_SIZE[0],
                pixel_pos[1] / TILE_SIZE[1])
        old_tile = self.level.get_tile(tile_pos)
        if self.tool == '.' and old_tile is None:
            return
        elif old_tile is not None and old_tile.tile_char == self.tool:
            return
        self.level.replace_tile(tile_pos, self.tool)