Importing Images
Goals
Importing and drawing images (imported as
pygame.Surface
)Extracting a
pygame.Rect
from the image to use as a game object (for collision and movement).- Understand transparency (png) and the importance of cropping your image files.
pygame.Surface.set_alpha(int) -> None
- Check pygame docs for various
pygame.transform
methods to use onpygame.Surface
s. pygame.transform.flip(surface: Surface, flip_x: bool, flip_y: bool) -> Surface
pygame.transform.scale(surface: Surface, size: Tuple[int, int], dest_surface: Surface = None) -> Surface
pygame.transform.rotate(surface: Surface, degrees: float) -> Surface
- Check pygame docs for various
Required Files
Video Tutorial
Not done yet, sorry.
What you need to do
When you click the fish make it grow. You will need to scale the image as well as update the
fish_rect
.Add the ability to move the fish left and right with the keyboard.
When the fish moves, flip the image to have the fish look in that direction.
Final Code
1# Importing Images
2
3import pygame
4
5
6pygame.init()
7
8WIDTH = 640
9HEIGHT = 480
10SIZE = (WIDTH, HEIGHT)
11
12screen = pygame.display.set_mode(SIZE)
13clock = pygame.time.Clock()
14
15# ---------------------------
16# Initialize global variables
17
18fish_img = pygame.image.load("fishGreen.png")
19fish_rect = fish_img.get_rect()
20fish_rect.center = screen.get_rect().center
21print(fish_rect)
22
23alpha = 255
24alpha_speed = -15
25
26flipped = pygame.transform.flip(fish_img, True, True)
27smaller = pygame.transform.scale(fish_img, (50, 50))
28rotated = pygame.transform.rotate(fish_img, 45)
29# ---------------------------
30
31running = True
32while running:
33 # EVENT HANDLING
34 for event in pygame.event.get():
35 if event.type == pygame.KEYDOWN:
36 if event.key == pygame.K_ESCAPE:
37 running = False
38 elif event.type == pygame.QUIT:
39 running = False
40 elif event.type == pygame.MOUSEBUTTONDOWN:
41 if fish_rect.collidepoint(event.pos):
42 print("fish clicked")
43 else:
44 print("fish NOT clicked")
45
46 # GAME STATE UPDATES
47 # All game math and comparisons happen here
48 alpha += alpha_speed
49 if alpha < 0 or alpha > 255:
50 alpha_speed *= -1
51 fish_img.set_alpha(alpha)
52
53 # DRAWING
54 screen.fill((255, 255, 255)) # always the first drawing command
55
56 screen.blit(fish_img, fish_rect.topleft)
57 pygame.draw.rect(screen, (100, 0, 0), fish_rect, 2) # draw hit-box
58
59 screen.blit(flipped, (0, 0))
60 screen.blit(smaller, (flipped.get_width(), 0))
61 screen.blit(rotated, (flipped.get_width() + smaller.get_width(), 0))
62
63 # Must be the last two lines
64 # of the game loop
65 pygame.display.flip()
66 clock.tick(30)
67 #---------------------------
68
69
70pygame.quit()