Beispiel #1
0
    def write(
            self,
            text,
            pos,
            color=(255, 255, 255),
            shadow=(0, 0, 0),
            shadow_offset=ivec2(1, 1),
            underline=False,
    ):
        pos = ivec2(*pos)

        if underline:
            self.font.set_underline(True)

        # shadow
        textbuf = self.font.render(text, True, shadow)
        self.screen.blit(
            textbuf,
            pos + ivec2(-textbuf.get_rect()[2] // 2 + shadow_offset[0],
                        shadow_offset[1]),
        )

        # text
        textbuf = self.font.render(text, True, color)
        self.screen.blit(textbuf, pos + ivec2(-textbuf.get_rect()[2] // 2, 0))

        if underline:
            self.font.set_underline(False)
Beispiel #2
0
 def move_to_player(self):
     pos_diff = self.player.pos - self.pos
     if abs(pos_diff.x) > abs(pos_diff.y):
         curr_speed = ivec2(copysign(1, pos_diff.x), 0)
     else:
         curr_speed = ivec2(0, copysign(1, pos_diff.y))
     self.direction = curr_speed
Beispiel #3
0
    def set_rotation(self, pressed_keys):
        if self.pos.x % SIZE_MODIFIER or self.pos.y % SIZE_MODIFIER:
            self.update()
            return

        old_direction = self.direction
        old_index = self.curr_dir_texture
        old_pos = ivec2(self.pos)

        if pressed_keys[pygame.K_w]:
            self.direction = ivec2(0, -1)
            self.curr_dir_texture = 0
        elif pressed_keys[pygame.K_a]:
            self.direction = ivec2(-1, 0)
            self.curr_dir_texture = 2
        elif pressed_keys[pygame.K_s]:
            self.direction = ivec2(0, 1)
            self.curr_dir_texture = 3
        elif pressed_keys[pygame.K_d]:
            self.direction = ivec2(1, 0)
            self.curr_dir_texture = 1
        self.update()

        if self.pos == old_pos:
            self.direction = old_direction
            self.curr_dir_texture = old_index
Beispiel #4
0
    def blit(self, img, pos=None, crop=None, paint=True):
        if isinstance(img, str):
            # load from filename
            fn = self.app.resource_path(img)
            img = self.app.cache(fn)
            pil_image = img.image()
        elif isinstance(img, ImageResource):
            pil_image = img.image()  # PIL.Image
            pass
        else:
            pil_image = img

        if pos is None:
            pos = ivec2(0, 0)
        else:
            pos = ivec2(*pos)

        csurf = img.cairo_surface = pil_to_cairo(pil_image)

        def f():
            self.cairo.set_source_surface(csurf, *pos)
            if paint:
                self.cairo.paint()

        self.on_render += f
        self.refresh()
Beispiel #5
0
    def get_animation(self, color):
        filename = path.join(SPRITES_DIR, "buttabomber.gif")

        # load an image if its not already in the cache, otherwise grab it
        # image: pygame.SurfaceType = self.app.load_img('BOSS')
        if "BOSS" not in self.app.cache:
            image = pygame.image.load(filename)
            image = pygame.transform.scale(image, ivec2(1024))
            self.app.cache["BOSS"] = image
        else:
            image = self.app.cache["BOSS"]

        brighter = color
        darker = pygame.Color("yellow")
        very_darker = pygame.Color("gold")

        palette = [(1, 0, 1), (0, 0, 0), brighter, darker, very_darker]

        image.set_palette(palette)
        image.set_colorkey((1, 0, 1))  # index 0

        self.width = image.get_width() // self.NB_FRAMES
        self.height = image.get_height()

        frames = [
            image.subsurface((self.width * i, 0, self.width, self.height))
            for i in range(self.NB_FRAMES)
        ]

        self.width = image.get_width() // self.NB_FRAMES
        self.height = image.get_height()
        self.size = ivec2(image.get_size())
        self.render_size = ivec2(image.get_size())

        return [image]
Beispiel #6
0
	def pixel(self, p):
		at = glm.ivec2(p // self.size)
		
		t = self.tile(at)
		if not t:
			return None
		t -= 1
		w = self.image.size.x // self.size

		return glm.ivec2(t % w, t // w) * self.size + glm.ivec2(p - at * self.size)
Beispiel #7
0
    def write_weapon_stats(self):
        if not self.alive:
            return

        if not self.hide_stats:
            ty = 0
            ofs = ivec2(0, 10)

            terminal = self.app.state.terminal

            wpn = self.weapons[self.current_weapon]
            # extra space here to clear terminal

            if wpn.max_ammo < 0:
                ammo = wpn.letter + " ∞"
            else:
                ammo = f"{wpn.letter} {wpn.ammo}/{wpn.max_ammo}"

            if len(ammo) < 10:
                ammo += " " * (10 - len(ammo))  # pad

            col = glm.mix(ncolor(wpn.color), ncolor("white"),
                          self.weapon_flash)
            self.game_state.terminal.write("      ", (1, ty), col)
            self.game_state.terminal.write(ammo, (1, ty), col, ofs)

            col = glm.mix(ncolor("red"), ncolor("white"), self.health_flash)
            # self.game_state.terminal.write(
            #     " " + "♥" * self.hp + " " * (3 - self.hp), 1, "red"
            # )
            self.game_state.terminal.write_center("      ", ty + 1, col)
            self.game_state.terminal.write_center("      ", ty, col)
            self.game_state.terminal.write_center(
                "♥" * self.hp + " " * (self.hp - self.max_hp), ty, "red", ofs)

            # Render Player's Score
            score_display = "Score: {}".format(self.stats.score)
            score_pos = (
                terminal.size.x - len(score_display) - 1,
                ty,
            )
            col = glm.mix(ncolor("white"), ncolor("yellow"), self.score_flash)
            self.game_state.terminal.write("        ", score_pos + ivec2(0, 1),
                                           col)
            self.game_state.terminal.write(score_display, score_pos, col, ofs)

            # self.game_state.terminal.write("WPN " + wpn.letter, (0,20), wpn.color)
            # if wpn.max_ammo == -1:
            #     self.game_state.terminal.write("AMMO " + str(wpn.ammo) + "  ", (0,21), wpn.color)
            # else:
            #     self.game_state.terminal.write("AMMO n/a  ", (0,21), wpn.color)
        else:
            self.game_state.terminal.clear(0)
 def __init__(
         self,
         text,
         imgs,
         pos=ivec2(0, 0),
         color=(255, 255, 255, 0),
         offset=ivec2(0, 0),
 ):
     self.imgs = imgs
     self.text = text
     self.pos = pos
     self.color = color
     self.offset = offset
Beispiel #9
0
    def result_drawing_func():
        if level.dot_count:
            curr_label = _label_text_lose
        else:
            curr_label = _label_text_win
        rect = ivec2(curr_label.get_rect()[2:])
        window.blit(curr_label, (ivec2(800, 600) - rect) / 2)

        curr_label = _label_text_result_remain
        window.blit(curr_label,
                    (ivec2(800, 600) - ivec2(curr_label.get_rect()[2:])) / 2 +
                    ivec2(0, rect.y))
        return level
    def render(self, camera):

        if self.dirty:

            # self.surface.fill((255,255,255,0), (0, 0, *self.app.size))

            for y in range(len(self.chars)):

                if not self.dirty_line[y]:
                    continue

                # clear line
                self.surface.fill(
                    self.bg_color,
                    (
                        0,
                        y * self.font_size.y - 3,
                        self.app.size.x + 6,
                        self.font_size.y + 6,
                    ),
                )

            for y in range(len(self.chars)):

                if not self.dirty_line[y]:
                    continue

                for x in range(len(self.chars[y])):
                    ch = self.chars[y][x]
                    if ch:
                        ofs = self._offset + ch.offset + self.spacing / 2
                        pos = ivec2(x, y) * self.font_size + ofs
                        pos.x = max(0, min(self.app.size.x, pos.x))
                        pos.y = max(0, min(self.app.size.y, pos.y))
                        self.surface.blit(
                            ch.imgs[1],
                            pos + ivec2(2, -2),
                        )
                        self.surface.blit(
                            ch.imgs[2],
                            pos + ivec2(-3, 3),
                        )
                        # text
                        self.surface.blit(ch.imgs[0], pos)
                    self.dirty_line[y] = False

            self.dirty = False

        self.app.screen.blit(self.surface, (0, 0))  # screen space
Beispiel #11
0
    def __init__(self,
                 app,
                 scene,
                 radius,
                 color="white",
                 damage=1,
                 spread=1,
                 **kwargs):
        super().__init__(app, scene, **kwargs)

        self.app = app
        self.scene = scene
        self.color = ncolor(color)
        self.radius = radius
        self.damage = damage  # 1dmg/sec
        self.spread = spread
        self.parent = None

        if self.damage:
            self.play_sound("explosion.wav")

        self.collision_size = self.size = vec3(radius)
        self.font_size = ivec2(24, 24)
        font_fn = "data/PressStart2P-Regular.ttf"

        self.font = self.app.load(
            font_fn + ":" + str(self.font_size.y),
            lambda: pygame.font.Font(font_fn, self.font_size.y, bold=True),
        )
        self.solid = True
Beispiel #12
0
    def __init__(self, app, scene, pos: vec3, z_vel: float, **kwargs):

        super().__init__(app,
                         scene,
                         None,
                         position=pos,
                         velocity=Z * 1000,
                         **kwargs)

        self._surface = None
        gcolor = self.scene.ground_color
        if gcolor:

            if "ROCK" not in self.app.cache:
                # self.color = ncolor("white")
                self._surface = pygame.Surface(ivec2(4))
                # self.color = ncolor("white")
                self._surface.fill(
                    pg_color(glm.mix(ncolor("black"), gcolor, 0.4)))
                # self._surface.fill((0,0,0))

                self.app.cache["ROCK"] = self._surface

                # self.velocity = Z * 10000 + z_vel
            else:
                self._surface = self.app.cache["ROCK"]
Beispiel #13
0
 def _winpos_to_bufpos(self, x, y):
     x = min(max(x, 0), RENDER_RESOLUTION)
     y = min(max(y, 0), RENDER_RESOLUTION)
     pos = vec2(x, RENDER_RESOLUTION - y)
     pos /= RENDER_RESOLUTION
     pos *= BUFFER_RESOLUTION * 2.0
     return ivec2(pos)
Beispiel #14
0
    def __init__(self, initial_state):
        """
        The main beginning of our application.
        Initializes pygame and the initial state.
        """

        # pygame.mixer.pre_init(44100, 16, 2, 4096)
        pygame.init()

        self.size = ivec2(1920, 1080) / 2
        """Display size"""
        self.cache = {}
        """Resources with filenames as keys"""
        pygame.display.set_caption("Butterfly Destroyers")
        self.screen = pygame.display.set_mode(self.size)
        self.on_event = Signal()
        self.quit = False
        self.clock = pygame.time.Clock()
        self.inputs = Inputs()
        self.time = 0
        self.dirty = True
        self.data = {}  # data persisting between modes
        # self.keys = [False] * self.MAX_KEYS

        self._state = None
        self.last_state = None
        self.next_state = initial_state
        self.process_state_change()
Beispiel #15
0
 def load_fn():
     img = pygame.image.load(os.path.join(SPRITES_DIR, filename))
     if scale != 1:
         w, h = img.get_size()
         img = pygame.transform.scale(img, ivec2(vec2(w, h) * scale))
         if flipped:
             img = pygame.transform.flip(img, True, False)
     return img
Beispiel #16
0
	def mousemove(self, p = None):
		"Call this when the mouse moves."
		
		# We don't need overloads of mousemoves
		# But we might want them for precision in some apps...
		if p:
			self._mouse_moved_this_tick = glm.ivec2(p)
		elif not self._mouse_moved_this_tick:
			self._mouse_moved_this_tick = True
    def write_right(self,
                    text,
                    pos=0,
                    color=vec4(1, 1, 1, 0),
                    offset=(0, 0),
                    length=0):
        """
        write() to screen right side
        """

        if isinstance(pos, (int, float)):
            # if pos is int, set row number
            pos = ivec2(0, pos)
        else:
            pos = ivec2(pos[0], pos[1])

        pos.x += self.size.x - 2
        return self.write(text, pos, color, offset, 1, len(text))
Beispiel #18
0
    def render(self, camera):
        self.write_weapon_stats()

        # Ship
        rect = self._surface.get_rect()

        rect.center = (self.app.size[0] / 2, self.app.size[1] * 0.8)
        direction = self.velocity.xy / self.speed.xy
        rect.center += direction * (10, -10)

        if self.visible:
            # stretch player graphic
            sz = ivec2(*self._surface.get_size())

            img = self._surface
            if self.velocity:
                sz.y += self.velocity.y / self.speed.y * 10
                img = pygame.transform.scale(self._surface, sz)

            if self.velocity.x:
                rot = -self.velocity.x / self.speed.x * 30
                img = pygame.transform.rotate(img, rot)

            nrect = (rect[0], rect[1], *sz)
            self.app.screen.blit(img, nrect)

        # Crosshair
        if self.alive:
            rect = self.crosshair_surf.get_rect()
            rect.center = self.app.size / 2

            if self.find_enemy_in_crosshair():
                if not self.targeting:
                    self.targeting = True  # triggers
                sz = ivec2(vec2(rect[2], rect[3]) * self.crosshair_scale)
                img = pygame.transform.scale(self.crosshair_surf_green, sz)
                rect[2] -= round(sz.x / 2)
                rect[3] -= round(sz.y / 2)
                self.app.screen.blit(img, rect)
            else:
                if self.targeting:
                    self.targeting = False  # triggers
                self.app.screen.blit(self.crosshair_surf, rect)
Beispiel #19
0
    def _init(self):
        from .camera import Camera, RenderLayer
        from .canvas import Canvas

        self.canvas_layer = self.camera.add(RenderLayer)
        self.canvas = self.canvas_layer.canvas = self.canvas_layer.add(
            Canvas(self, res=ivec2(1920, 1080), scale=self.app.scale))

        # TODO: add signal on resize
        # self.console_layer = camera.add(RenderLayer)
        # self.console = self.console_layer.console = self.console_layer.add(Canvas(self, res=ivec2(1920,1080), scale=self.scale))

        self.backdrop_layer = self.scene.backdrop = RenderLayer(
            self, camera=self.camera)
        self.backdrop = self.backdrop_layer.canvas = self.backdrop_layer.add(
            Canvas(self, res=ivec2(1920, 1080), scale=self.app.scale))

        if hasattr(self, "script"):
            self.add_script(self.script)
Beispiel #20
0
    def __init__(self, app, scene, pos: vec3, z_vel: float):
        vel = vec3(0, 0, z_vel)

        super().__init__(app, scene, None, position=pos, velocity=vel)

        self._surface = self.app.load(
            "STAR", lambda: pygame.Surface(ivec2(4)).convert()
        ).copy()
        self._surface.fill((255, 255, 255))
        self._surface.set_alpha(50)
Beispiel #21
0
	def __init__(self, *args, **kwargs):
		if kwargs:
			self.resolution = kwargs.get('resolution', glm.ivec2(0, 0))
			self.position = kwargs.get('position', glm.vec3(.0, .0, .0))
			self.up = kwargs.get('up', glm.vec3(.0, 1.0, .0))
			self.look_at = kwargs.get('look_at', glm.vec3(.0, .0, -1.0))
		elif args:
			self.resolution, self.position, self.up, self.look_at = args
		else:
			self.resolution = glm.ivec2(0, 0)
			self.position = glm.vec3(.0, .0, .0)
			self.up = glm.vec3(.0, 1.0, .0)
			self.look_at = glm.vec3(.0, .0, -1.0)

		# Camera direction
		self.direction = glm.normalize((self.look_at - self.position))

		# The camera uses an orthonormal basis
		self.onb = onb.ONB()
		self.onb.setFromUW(glm.normalize(glm.cross(self.up, -self.direction)), -self.direction)
Beispiel #22
0
 def _parse_entities(self, lines):
     for i in range(len(lines)):
         if not lines[i]:
             return lines[i + 1:]
         entity, x, y = lines[i].split(' ')
         pos = ivec2(int(x), int(y)) * SIZE_MODIFIER
         if entity == 'player':
             self.entities['player'] = Player(self, pos)
         else:
             self.entities['ghost'].append(
                 Ghost(self, self.entities['player'], pos))
 def __init__(self, *args, **kwargs):
     if kwargs:
         self.min_x = kwargs.get('min_x', 0.0)
         self.max_x = kwargs.get('max_x', 0.0)
         self.min_y = kwargs.get('min_y', 0.0)
         self.max_y = kwargs.get('max_y', 0.0)
         self.camera = kwargs.get(
             'camera',
             camera.Camera(glm.ivec2(0, 0), glm.vec3(.0, .0, .0),
                           glm.vec3(.0, .0, .0), glm.vec3(.0, .0, .0)))
     elif args:
         self.min_x, self.max_x, self.min_y, self.max_y, self.camera = args
     else:
         self.min_x = 0.0
         self.max_x = 0.0
         self.min_y = 0.0
         self.max_y = 0.0
         self.camera = camera.Camera(glm.ivec2(0, 0), glm.vec3(.0, .0, .0),
                                     glm.vec3(.0, .0, .0),
                                     glm.vec3(.0, .0, .0))
Beispiel #24
0
    def __init__(self, app, scene, pos: vec3, z_vel: float, **kwargs):

        super().__init__(app, scene, None, position=pos, **kwargs)

        filled = "RAIN" in self.app.cache

        self._surface = self.app.load(
            "RAIN", lambda: pygame.Surface(ivec2(2, 24)).convert())
        if not filled:
            self._surface.fill(pg_color("lightgray"))

        self.velocity = vec3(0, -1000, 1000 + z_vel)
Beispiel #25
0
    def __init__(self, gl, width, height, volume_res):
        super(Context, self).__init__()
        self.gl = gl
        self._vaos = []

        self.u_res = glm.ivec2(width, height)
        self.u_vsize = glm.ivec3(volume_res)
        self.gx, self.gy, self.gz = (
            int(self.u_vsize.x / 4),
            int(self.u_vsize.y / 4),
            int(self.u_vsize.z / 4),
        )
    def __init__(self, app, scene, text, color, **kwargs):
        super().__init__(app, scene, **kwargs)

        self.app = app
        self.scene = scene

        self.collision_size = self.size = vec3(24 * len(text), 24, 150)
        self.font_size = ivec2(24, 24)

        self.shadow_color = pygame.Color(120, 120, 120, 0)
        self.shadow2_color = pygame.Color(0, 0, 0, 0)

        self.set(text, color)
Beispiel #27
0
    def update(self, dt):
        cube_faces = self.led_cube.getCubeArrayAsColour([0.1, 0.1, 0.1])

        for p in self.particles:
            p.update(dt)
            face_id, uv_vec = getIndexFromSphereCoords(p.pos.x, p.pos.y)
            uv_vec = glm.ivec2(glm.floor(uv_vec * self.led_cube.size))
            cube_faces[face_id, uv_vec.x, uv_vec.y] = p.getColourFaded()

        self.led_cube.updateFaces(cube_faces)
        self.led_cube.update()

        self.led_cube.rotateAngleAxis(dt * 0.1, glm.vec3(0, 0, 1))
Beispiel #28
0
    def render(self, camera):
        if not self.visible:
            return

        pos = self.position

        half_diag = vec3(-self.radius, self.radius, 0)
        world_half_diag = camera.rel_to_world(half_diag) - camera.position

        pos_tl = camera.world_to_screen(pos + world_half_diag)
        pos_bl = camera.world_to_screen(pos - world_half_diag)

        if None in (pos_tl, pos_bl):
            # behind the camera
            self.scene.remove(self)
            return

        size = ivec2(pos_bl.xy - pos_tl.xy)

        # max_fade_dist = camera.screen_dist * FULL_FOG_DISTANCE
        # alpha = surf_fader(max_fade_dist, camera.distance(pos))

        # self.app.screen.blit(surf, ivec2(pos_tl))

        # col = glm.mix(ncolor(self.color), self.app.state.scene.sky_color, alpha)

        # rad = (camera.position.z - self.position.z)/1000 * self.radius
        # if rad < 0:
        #     self.remove()
        #     return

        screen_pos = ivec2(pos_tl) + size
        pygame.gfxdraw.filled_circle(
            self.app.screen,
            int(abs(screen_pos.x - size.x / 2)),
            int(abs(screen_pos.y - size.y / 2)),
            int(abs(size.x)),
            pg_color(self.color),
        )
    def __init__(self, app, scene, size=None):
        super().__init__(app, scene)

        self.app = app
        self.scene = scene

        self.font_size = ivec2(size or 24)
        self.spacing = ivec2(0)
        font_fn = path.join(FONTS_DIR, "PressStart2P-Regular.ttf")

        # load the font if its not already loaded (cacheble)
        # we're appending :16 to cache name since we may need to cache
        # different sizes in the future
        self.font = self.app.load(
            (font_fn, self.font_size.y),
            lambda: pygame.font.Font(font_fn, self.font_size.y, bold=True),
        )

        # terminal size in characters
        self.size = app.size / (self.font_size + self.spacing)

        # dirty flags for lazy redrawing
        self.dirty = True
        self.dirty_line = [True] * self.size.y  # dirty flags per line

        self._offset = ivec2(0, 0)

        # 2d array of pygame text objects
        self.chars = []
        for y in range(self.size.y):
            self.chars.append([None] * self.size.x)

        self.surface = pygame.Surface(self.app.size, pygame.SRCALPHA,
                                      32).convert_alpha()

        self.bg_color = ivec4(255, 255, 255, 0)  # transparent by default
        self.shadow_color = ivec4(120, 120, 120, 0)
        self.shadow2_color = ivec4(0, 0, 0, 0)
Beispiel #30
0
 def load_svg(self, fn, sz):
     surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *sz)
     ctx = cairo.Context(surface)
     svg = rsvg.Handle.new_from_file(fn)
     dim = svg.get_dimensions()
     dim = ivec2(dim.width, dim.height)
     scale = sz[0] / dim[0]
     ctx.scale(scale, scale)
     svg.render_cairo(ctx)
     im = Image.frombuffer("RGBA", tuple(sz),
                           surface.get_data().tobytes(), "raw", "BGRA", 0,
                           0)
     buf = im.tobytes()
     return pygame.image.fromstring(buf, sz, "RGBA").convert_alpha()
Beispiel #31
0
	def draw(self, v1, v2):
		basic.image(self.image)
		vv1 = glm.ivec2(v1 / self.size // self.chunkSize)
		vv2 = glm.ivec2((v2 + self.chunkSize / 2) / self.size // self.chunkSize) + 1
		
		w = self.image.size / self.size
		s = glm.vec2(1) / w
		
		rcs = range(self.chunkSize)
		
		lt = None
		
		for y in range(vv1.y, vv2.y):
			for x in range(vv1.x, vv2.x):
				c = glm.ivec2(x, y)
				if c in self.chunks:
					cc = self.chunks[c]
					ccc = c * self.size * self.chunkSize
					for yy in rcs:
						ccyy = cc[yy]
						for xx in rcs:
							t = ccyy[xx]
							if t:
								p1 = ccc + glm.ivec2(xx, yy) * self.size
								if(p1.x + self.size < v1.x or p1.y + self.size < v1.y or p1.x > v2.x or p1.y > v2.y):
									continue
								
								t -= 1
								
								if lt != t:
									t1 = glm.vec2(t % w.x, t // w.x) / w
									basic.texcoord(t1, t1 + s)
								
								lt = t
								
								basic.quad(p1, p1 + self.size)
    def write_center(
            self,
            text,
            pos=0,
            color=vec4(1, 1, 1, 0),
            offset=(0, 0),
            length=0,
            char_offset=(0, 0),
    ):
        """
        write() to screen center X on row `pos`

        :param char_offset: Shift the text by this offset after centering
        """
        if isinstance(pos, (int, float)):
            # if pos is int, set col number
            pos = ivec2(0, pos)
        else:
            pos = ivec2(pos[0], pos[1])

        # print(pos)
        pos.x -= self.size.x / 2
        pos += char_offset
        return self.write(text, pos, color, offset, 0, length)
Beispiel #33
0
    def menu_drawing_func():
        # drawing header
        window.blit(_label_text_select_file,
                    (400 - _label_text_select_file.get_rect()[2] // 2, 0))
        curr_height_offset = _label_text_select_file.get_rect()[3]

        # drawing list and triangle
        for i, (text, surface) in enumerate(maps):
            window.blit(surface,
                        (400 - surface.get_rect()[2] // 2, curr_height_offset))
            if i == curr_selected_surface[0]:
                pos = ivec2(20, curr_height_offset + 5)
                pygame.draw.polygon(
                    window, (255, 60, 60),
                    [pos, pos + ivec2(0, 50), pos + ivec2(50, 25)])
            curr_height_offset += surface.get_rect()[3]

        if pygame.key.get_pressed()[pygame.K_DOWN]:
            curr_selected_surface[0] += 1
        if pygame.key.get_pressed()[pygame.K_UP]:
            curr_selected_surface[0] -= 1
        curr_selected_surface[0] %= len(maps)
        if pygame.key.get_pressed()[pygame.K_SPACE]:
            return Map(window, join('maps', maps[curr_selected_surface[0]][0]))
Beispiel #34
0
	def __init__(self, w, e = None):
		# List of callbacks that will be handled
		self.timeouts = []
		
		# Window of the interface
		self.window = w
		
		# Current element that has focus
		self.active = None
		
		# Element the mouse is over
		self.over = None
		
		# Active drag
		self.dragging = None
		
		# Element that is capturing all events, if any
		self.captured = None
		
		# For clicked
		self.last_down_on = None
		self.last_down_on_b = -1
		
		# Mouse position caches
		self.mouse_position_in_over = None
		self.mouse_global = glm.ivec2(0, 0)
		self._mouse_moved_this_tick = False
		
		# There is a delay when changing the element to scroll so the mouse doesn't get caught
		self.scroll_element = None
		self.scroll_time = 0
		self.scroll_timeout = 1
		
		self._refitting_state = False
		self.mess = set()
		
		# Root element
		if e:
			self.body = e(self)
		else:
			# Default body shall be solid clear color
			self.body = Element(self)
			self.body.draw = lambda: self.interface.window.color()
			self.body.soliddraw = True
		
		# Default to covering the whole window
		self.body.style.size = Offset(*w.size())
Beispiel #35
0
	def tileAt(self, p, v = None):
		return self.tile(glm.ivec2(p / self.size), v)
Beispiel #36
0
	def overlapping(self, p1, p2):
		p = glm.ivec2()
		for p.x in range(int(p1.x // self.size), int(p2.x // self.size) + 1):
			for p.y in range(int(p1.y // self.size), int(p2.y // self.size) + 1):
				yield (self.tile(p), p)
		raise StopIteration
Beispiel #37
0
def _setup(wd):
	global _wd, _program, _font_program, _vao, _font_vbo, _font_vao, _vbo, _initstate, _matrix, _white, _img, _color
	
	_wd = wd
	
	_font_vshader = scge.shader('vertex', '''#version 330 core
	
	in vec2 coords;
	in vec2 texcoords;

	uniform mat4 matrix;
	
	out vec2 texcoord;

	void main() {
		texcoord = texcoords;
	
		gl_Position = matrix * vec4(coords, 0.0, 1.0);
	}
	''')
	
	_font_fshader = scge.shader('fragment', '''#version 330 core
	#extension GL_ARB_texture_rectangle : require
	
	in vec2 texcoord;
	
	uniform sampler2DRect tex;
	uniform vec4 color;

	out vec4 frag;

	void main() {
		frag = color;
		frag.a *= texture2DRect(tex, texcoord).r;
		if(frag.a == 0.)
			discard;
	}
	''')

	_font_program = scge.program()
	_font_program.attach(_font_vshader)
	_font_program.attach(_font_fshader)
	_font_program.attribute(0, 'coords')
	_font_program.attribute(1, 'texcoords')
	_font_program.attribute(2, 'ink')
	_font_program.link()
	
	_vshader = scge.shader('vertex', '''#version 330 core
	in vec2 coords;
	in vec4 colors;
	in vec2 texcoords;

	uniform mat4 matrix;

	out vec4 color;
	out vec2 texcoord;

	void main() {
		color = colors;
		texcoord = texcoords;
	
		gl_Position = matrix * vec4(coords, 0.0, 1.0);
	}
	''')

	_fshader = scge.shader('fragment', '''#version 330 core
	in vec4 color;
	in vec2 texcoord;
	
	uniform sampler2D tex;

	out vec4 frag;

	void main() {
		frag = texture2D(tex, texcoord) * color;
		if(frag.a == 0.)
			discard;
	}
	''')
	
	_program = scge.program()
	_program.attach(_vshader)
	_program.attach(_fshader)
	_program.attribute(0, 'coords')
	_program.attribute(1, 'colors')
	_program.attribute(2, 'texcoords')
	_program.link()

	_vbo = scge.vbo(s_f8_4, 'stream draw')

	_vao = scge.vao()
	_wd.use(_vao)
	_vao.enable(0)
	_vao.enable(1)
	_vao.enable(2)
	_vao.attribute(0, _vbo, 'float', 2, 0)
	_vao.attribute(1, _vbo, 'float', 4, s_f2_4)
	_vao.attribute(2, _vbo, 'float', 2, s_f6_4)
	
	_font_vbo = scge.vbo(s_f6_4, 'stream draw')
	
	_font_vao = scge.vao()
	_wd.use(_font_vao)
	_font_vao.enable(0)
	_font_vao.enable(1)
	_font_vao.attribute(0, _font_vbo, 'float', 2, 0, s_f * 4)
	_font_vao.attribute(1, _font_vbo, 'float', 4, s_f * 2, s_f * 4)
	
	p = scge.pixelcache(glm.ivec2(1, 1))
	p.pixel(glm.ivec2(0, 0), glm.vec4(1))
	_white = scge.image(p)
	
	_program.uniform('tex', _white)
	_img = _white
	
	_matrix = glm.ortho(0, wd.size().x, 0, wd.size().y, -1, 1)
	
	_usingDefaultProgram = True
	
	color(glm.vec4(1))
	
	_initstate = 1
Beispiel #38
0
	def _mousemove(self, p):
		# Moving the mouse cancels the scroll timeout
		self.scroll_time = 0
		
		# Calling mousemove() with no position arguments assumes the mouse moved in z
		if p is not None:
			self.mouse_global = glm.ivec2(p)
			if self.dragging:
				self.body.dirty = True
		else:
			if not self.mouse_global:
				return
			p = self.mouse_global
		
		# Captures get all mousemove events
		if self.captured:
			go = self.captured.globalOffset()
			mouse_position_in_over = p - go
			
			if self.mouse_position_in_over != mouse_position_in_over:
				self.mouse_position_in_over = mouse_position_in_over
				if self.over is not self.captured:
					if self.over:
						self.over.mouseoff()
					self.over = self.captured
					self.over.mouseon(Offset(*self.mouse_position_in_over))
			
				self.captured.mousemove(Offset(*self.mouse_position_in_over))
			return
		
		# Find the element the mouse is now on
		over, go = self.body.getElementAt(Offset(p.x - self.body.style.offset.x, p.y - self.body.style.offset.y))
		
		if over is None and self.over is None:
			return
		
		if go is not None:
			go += self.body.style.offset
		
		# Handle move events
		if over is self.over:
			mouse_position_in_over = p - go
			if mouse_position_in_over != self.mouse_position_in_over:
				self.mouse_position_in_over = mouse_position_in_over
				if self.dragging:
					self.over.dragmove(self.dragging.drag, Offset(*mouse_position_in_over))
				else:
					self.over.mousemove(Offset(*mouse_position_in_over))
		else:
			if self.over:
				if self.dragging:
					self.over.dragoff()
				else:
					self.over.mouseoff()
			self.over = over
			if self.over:
				self.mouse_position_in_over = p - go
				if self.dragging:
					self.over.dragon(self.dragging.drag)
					self.over.dragmove(self.dragging.drag, Offset(*self.mouse_position_in_over))
				else:
					self.over.mouseon()
					self.over.mousemove(Offset(*self.mouse_position_in_over))