ThePythonGameBook

learn Python. Create Games

User Tools

Site Tools


en:pygame:step004

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
en:pygame:step004 [2020/05/14 16:12]
Horst JENS [004_alphademo.py]
en:pygame:step004 [2020/05/15 22:38] (current)
Horst JENS
Line 393: Line 393:
     alphademo()     alphademo()
 </​code>​ </​code>​
-==== 004_alphademo_pretty.py ==== 
  
-This program need other graphic files to be located in a subfolder called ''​data''​. See the file table above for details. To get the program working correctly, you best download and unpack the whole file archive (link in the file table above). 
- 
-<note tip>This version is for python 2.x only ! For python 3.x, see the next code example below</​note>​ 
- 
-View/​Edit/​Download the file directly in Github: https://​github.com/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​004_alphademo_pretty.py ​ 
- 
-<​html>​ 
- <​script src="​http://​gist-it.appspot.com/​github/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​004_alphademo_pretty.py">​ 
- </​script></​html>​ 
  
 ==== 004_alphademo_pretty_python3x.py ==== ==== 004_alphademo_pretty_python3x.py ====
Line 415: Line 405:
 View/​Edit/​Download the file directly in Github: https://​github.com/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​004_alphademo_pretty_python3x.py View/​Edit/​Download the file directly in Github: https://​github.com/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​004_alphademo_pretty_python3x.py
  
-<html+<code python
- <script src="​http:​//gist-it.appspot.com/github/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​004_alphademo_pretty_python3x.py">​ +#!/usr/bin/env python
- </​script></​html>​+
  
 +"""​
 +004_alphademo_pretty.py
 +Experiments with colorkey and alpha-value
 +URL: http://​thepythongamebook.com/​en:​part2:​pygame:​step004
 +Author: horst.jens@spielend-programmieren.at,​ prettifying by yipyip
 +per-pixel-alpha code by Claudio Canepa <​ccanepacc@gmail.com>​
 +Licence: gpl, see http://​www.gnu.org/​licenses/​gpl.html
  
 +works with pyhton2.7
 +"""​
 +
 +####
 +
 +import pygame
 +import os
 +import itertools
 +
 +
 +
 +####
 +
 +BLENDMODES = ((pygame.BLEND_ADD,​ "​ADD"​),​
 +              (pygame.BLEND_SUB,​ "​SUB"​),​
 +              (pygame.BLEND_MULT,​ "​MULT"​),​
 +              (pygame.BLEND_MIN,​ "​MIN"​),​
 +              (pygame.BLEND_MAX,​ "​MAX"​),​
 +              (pygame.BLEND_RGBA_ADD,​ "RGBA ADD"),
 +              (pygame.BLEND_RGBA_SUB,​ "RGBA SUB"),
 +              (pygame.BLEND_RGBA_MULT,​ "RGBA MULT"​),​
 +              (pygame.BLEND_RGBA_MIN,​ "RGBA MIN"),
 +              (pygame.BLEND_RGBA_MAX,​ "RGBA MAX"))
 +
 +####
 +
 +def load_pic(name,​ path="​data"​):​
 +
 +    return pygame.image.load(os.path.join(path,​ name))
 +
 +####
 +
 +def check(x, minval=0, maxval=255):​
 +
 +    return min(maxval, max(minval, x))
 +    ​
 +####
 + 
 +def get_alpha_surface(surface,​ rgba=(128, 128, 128, 128), mode=pygame.BLEND_RGBA_ADD):​
 +    """​
 +    Return a copy of a surface object with user-defined ​
 +    values for red, green, blue and alpha. Values from 0-255. ​
 +    (Thanks to Claudio Canepa <​ccanepacc@gmail.com>​)
 +    """  ​
 +    new_surface = pygame.Surface(surface.get_size(),​ pygame.SRCALPHA|pygame.HWSURFACE)
 +    new_surface.fill(rgba)
 +    new_surface.blit(surface,​ (0, 0), surface.get_rect(),​ mode)
 +    ​
 +    return new_surface
 +
 +####
 +
 +class AlphaDemo(object):​
 +
 +
 +    def __init__(self,​ width=900, height=600, fontsize=14):​
 +
 +        pygame.init()
 +        self.screen = pygame.display.set_mode((width,​ height), pygame.DOUBLEBUF)
 +        self.background = pygame.Surface(self.screen.get_size()).convert()
 +        self.font = pygame.font.SysFont('​mono',​ fontsize, bold=True)
 +        self.clock = pygame.time.Clock()
 +        ​
 +        #​self.background.fill((255,​ 255, 255))
 +        venus = load_pic("​800px-La_naissance_de_Venus.jpg"​).convert()
 +        # transform venus and blit 
 +        pygame.transform.scale(venus,​ (width, height), self.background)
 +        ​
 +        # .png and .gif graphics can have transparency,​ use convert_alpha()
 +        self.png_monster = load_pic("​colormonster.png"​).convert_alpha()
 +        ​
 +        # jpg image, no transparency!
 +        self.jpg_monster = load_pic("​colormonster.jpg"​).convert()
 +
 +        # per pixel rgba
 +        self.pp_rgba = [255, 255, 255, 128]
 +        alpha_up = range(0, 256, 4)
 +        alpha_down = alpha_up[-1::​-1]
 +        self.glob_alphas = itertools.cycle(alpha_up + alpha_down)
 +        self.step = 4
 +        self.mode_nr = 5
 +
 +
 +    def run(self):
 +        """​
 +        Mainloop
 +        """​
 +        mainloop = True
 +        while mainloop:
 +            self.clock.tick(20)
 +            # draw background every frame
 +            self.screen.blit(self.background,​ (0, 0))
 +            ​
 +            for event in pygame.event.get():​
 +                if event.type == pygame.QUIT:​
 +                    mainloop = False
 +                elif event.type == pygame.KEYDOWN:​
 +                    if event.key == pygame.K_ESCAPE:​
 +                        mainloop = False
 +
 +            self.action(pygame.key.get_pressed())
 +            pygame.display.flip()
 +           
 +
 +    def action(self,​ pressed_keys):​
 +
 +        red, green, blue, alpha = self.pp_rgba
 +        if pressed_keys[pygame.K_PAGEUP]: ​
 +            blue = blue + self.step
 +        if pressed_keys[pygame.K_PAGEDOWN]: ​
 +            blue = blue - self.step ​   ​
 +        if pressed_keys[pygame.K_HOME]:​
 +            green = green + self.step ​   ​
 +        if pressed_keys[pygame.K_END]:​
 +            green = green - self.step
 +        if pressed_keys[pygame.K_INSERT]:​
 +            red = red + self.step ​   ​
 +        if pressed_keys[pygame.K_DELETE]:​
 +            red = red - self.step ​  
 +        if pressed_keys[pygame.K_KP_PLUS]:​
 +            alpha = alpha + self.step  ​
 +        if pressed_keys[pygame.K_KP_MINUS]:​
 +            alpha = alpha - self.step
 +        if pressed_keys[pygame.K_RETURN]:​
 +            self.mode_nr = (self.mode_nr + 1) % len(BLENDMODES) ​   ​
 +        ​
 +        mode, mode_text = BLENDMODES[self.mode_nr]
 +        self.pp_rgba = map(check, (red, green, blue, alpha)) ​      
 +        glob_alpha = self.glob_alphas.next()
 +        self.show_surfaces(self.png_monster,​ '​png',​ 0, 0, 200, 180,
 +                           ​glob_alpha,​ self.pp_rgba,​ mode)
 +        self.show_surfaces(self.jpg_monster,​ '​jpg',​ 0, 300, 200, 180,
 +                           ​glob_alpha,​ self.pp_rgba,​ mode)
 +
 +        text = "​ins/​del=red>​%d ​ home/​end=green>​%d ​ pgup/​pgdwn=blue>​%d ​ "\
 +               "​+/​-=ppalpha>​%d ​ " % tuple(self.pp_rgba)
 +        pygame.display.set_caption("​%s ​ Mode>​%s"​ % (text, mode_text))
 +      ​
 +  ​
 +    def show_surfaces(self,​ surf, pictype, x, y, x_delta, height,
 +                      glob_alpha, pp_rgba, mode):
 +
 +        yh = y + height
 +        #pure surface
 +        self.screen.blit(surf,​ (x, y))
 +        self.write(x,​ y + height, "%s pure" % pictype)
 +        # with with colorkey
 +        ck_surf = surf.copy()
 +        ck_surf.set_colorkey((255,​255,​255))
 +        x = x + x_delta
 +        self.screen.blit(ck_surf,​ (x, y))
 +        self.write(x,​ yh, "%s colorkey"​ % pictype)
 +        # with alpha for whole surface ​
 +        alpha_surf = surf.copy()
 +        alpha_surf.set_alpha(glob_alpha)
 +        x = x + x_delta
 +        self.screen.blit(alpha_surf,​ (x, y))
 +        self.write(x,​ yh, "%s alpha> %d" % (pictype, glob_alpha))
 +        # with per-pixel alpha
 +        ppa_surf = surf.copy()
 +        ppa_surf = get_alpha_surface(ppa_surf,​ pp_rgba, mode)
 +        x = x + x_delta
 +        self.screen.blit(ppa_surf,​ (x, y))
 +        self.write(x,​ yh, "%s, per-pixel-alpha"​ % pictype)
 +
 +
 +    def write(self, x, y, msg, color=(255,​255,​0)):​
 +
 +        self.screen.blit(self.font.render(msg,​ True, color), (x, y))
 +            ​
 +####
 +        ​
 +if __name__ == "​__main__":​
 +    ​
 +    AlphaDemo().run()
 +
 +</​code>​
  
  
Line 430: Line 603:
 Note: For Python 3.x, change the two instances of the xrange() function (which was deprecated in Python 3) to range(). Note: For Python 3.x, change the two instances of the xrange() function (which was deprecated in Python 3) to range().
  
-<html+<code python
- <script src="​http://​gist-it.appspot.com/github/horstjens/ThePythonGameBook/blob/master/pygame/004_per-pixel-alphademo.py"> +#​!/​usr/​bin/​env python 
- </script></html> + 
-https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/004_per-pixel-alphademo.py  +"""​ 
-\\ +004_per-pixel-alphademo.py 
-\\ + 
-\\ +Experiments with alpha values. 
-\\+Use mouse and scrollwheel. 
 + 
 +URL:     http://thepythongamebook.com/en:​part2:​pygame:​step004 
 +Author: ​ Dirk Ketturkat 
 +License: Do What The Fuck You Want To Public License (WTFPL) 
 +         See http://sam.zoy.org/wtfpl/ 
 +"""​ 
 + 
 +#### 
 + 
 +import pygame 
 +import os 
 + 
 +#### 
 + 
 +def load_pic(name,​ path="​data"​):​ 
 + 
 +    pic = pygame.image.load(os.path.join(path,​ name)) 
 +    if pic.get_alpha():​ 
 +        return pic.convert_alpha() 
 +    else: 
 +        return pic.convert() 
 + 
 +#### 
 + 
 +def check(x, minval=0, maxval=255):​ 
 + 
 +    return min(maxval, max(minval, x)) 
 + 
 +#### 
 + 
 +def offset(len1,​ len2): 
 +    """​ For picture centering 
 +    """​ 
 +    return max(0, (len1 - len2) // 2) 
 + 
 +#### 
 + 
 +class PeepDemo(object):​ 
 + 
 + 
 +    def __init__(self,​ **opts): 
 + 
 +        ​pygame.init() 
 +        self.width = opts['​width'​] 
 +        self.height = opts['​height'​] 
 +        self.fps = opts['​fps'​] 
 +        self.screen = pygame.display.set_mode((self.width,​ self.height),​ pygame.DOUBLEBUF) 
 +        self.clock = pygame.time.Clock() 
 +        pygame.display.set_caption("​Move Mouse and Scroll Mouse Wheel"​) 
 + 
 +        self.pic = load_pic(opts['​pic'​]) 
 +        self.background = pygame.Surface(self.screen.get_size()).convert() 
 +        self.background.fill(opts['​backcol'​]) 
 + 
 +        self.ppa_surface = pygame.Surface(self.screen.get_size(),​ flags=pygame.SRCALPHA) 
 +        self.pic_offset = offset(self.width,​ self.pic.get_width()),​\ 
 +                          offset(self.height,​ self.pic.get_height()) 
 + 
 +        # init stuff for circles with alpha value 
 +        self.center = self.width ​// 2, self.height // 2 
 +        self.max_radius = min(self.width,​ self.height) 
 +        self.hole_count = opts['​holes'​] 
 +        self.calc_centers(self.center,​ self.center,​ self.hole_count) 
 +        self.calc_rad_alphas(self.max_radius,​ self.hole_count) 
 + 
 + 
 +    def calc_rad_alphas(self,​ radius, n): 
 +        ""​
 +        ​Calculate linear radius and alpha values 
 +        """​ 
 +        assert 0 256, "​Invalid number of holes!"​ 
 + 
 +        rad_step = radius ​// n 
 +        ​alpha_step = 256 // 
 +        self.rad_alphas = [(radius - i * rad_step, 255 - i*alpha_step) for i in xrange(n)] 
 + 
 + 
 +    def calc_centers(self,​ center, pos, holes): 
 +        """​ 
 +        Calculate center points from center (of window) to mouse position 
 +        """​ 
 + 
 +        cx, cy = center 
 +        mx, my = pos 
 +        vx, vy = mx - cx, my - cy 
 + 
 +        xs = vx // holes 
 +        ys = vy // holes 
 +        self.centers = [(cx + xs*i, cy + ys*i) for i in xrange(holes)] 
 + 
 + 
 +    def run(self):​ 
 +        """​ 
 +        Mainloop 
 +        """​ 
 +        mainloop = True 
 +        while mainloop: 
 +            self.flip() 
 +            for event in pygame.event.get():​ 
 +                if event.type == pygame.QUIT:​ 
 +                    mainloop = False 
 +                elif event.type == pygame.KEYDOWN:​ 
 +                    if event.key == pygame.K_ESCAPE:​ 
 +                        mainloop = False 
 +                elif event.type == pygame.MOUSEMOTION:​ 
 +                    self.calc_centers(self.center,​ pygame.mouse.get_pos(),​ 
 +                                      self.hole_count) 
 +                elif event.type == pygame.MOUSEBUTTONDOWN:​ 
 +                    # check mouse wheel 
 +                    if event.button in (4, 5): 
 +                        self.hole_count = check(self.hole_count+ [-1, 1][event.button-4], 
 +                                                2, 64) 
 +                        self.calc_rad_alphas(self.max_radius,​ self.hole_count) 
 +                        ​self.calc_centers(self.center,​ pygame.mouse.get_pos(),​ 
 +                                          ​self.hole_count) 
 + 
 +            ​self.show() 
 +        pygame.quit() 
 + 
 + 
 +    def show(self):​ 
 +        """​ 
 +        Draw all 
 +        """​ 
 + 
 +        # picture on screen 
 +        self.screen.blit(self.pic,​ self.pic_offset) 
 +        # circles on alpha surface 
 +        for (r, a), c in zip(self.rad_alphas,​ self.centers):​ 
 +            pygame.draw.circle(self.ppa_surface,​ (0, 0, 0, a), c, r) 
 + 
 +        # alpha surface on screen 
 +        self.screen.blit(self.ppa_surface,​ (0, 0)) 
 +        # erase alpha surface for new circles 
 +        self.ppa_surface.fill((0,​ 0, 0)) 
 + 
 + 
 +    def flip(self):​ 
 +        """​ 
 +        Show drawing and erase 
 +        """​ 
 +        pygame.display.flip() 
 +        self.screen.blit(self.background,​ (0, 0)) 
 +        self.clock.tick(self.fps) 
 + 
 +#### 
 + 
 +opts = {'​width':​ 800, 
 +        '​height':​ 600, 
 +        '​backcol':​ (255, 0, 0), 
 +        '​fps':​ 100, 
 +        '​fontsize':​ 18, 
 +        '​pic':​ '​ente.jpg',​ 
 +        '​holes':​ 7} 
 +#### 
 + 
 +if __name__ == "​__main__":​ 
 + 
 +    PeepDemo(**opts).run() 
 + 
 +</​code>​
  
 ^ [[:​en:​pygame:​step003| ← previous]] ^ [[en:start| ↑ Overview]] ^ [[:​en:​pygame:​step005| → next ]] ^ ^ [[:​en:​pygame:​step003| ← previous]] ^ [[en:start| ↑ Overview]] ^ [[:​en:​pygame:​step005| → next ]] ^
/var/www/horst/thepythongamebook.com/data/pages/en/pygame/step004.txt · Last modified: 2020/05/15 22:38 by Horst JENS