Faster drawing in python pygame - python

I made a program using Python, with pygame, that loads pictures of materials and then creates blocks and each block is assigned with random material.
Block is a class and in the drawing process, it iterates through the array with stored blocks, but that is very slow. Isn't there a faster method than storing them in array and iterating through?
class block:
def __init__(self, texture, x, y):
self.texture = texture
self.x = x
self.y = y
material = pygame.image
material.grass = pygame.image.load("textures/grass.png")
material.water = pygame.image.load("textures/water.png")
material.sand = pygame.image.load("textures/sand.png")
materials = [material.grass, material.water, material.sand]
white = (255,255,255);(width, height) = (2048, 1008);black = (0, 0, 0);screen = pygame.display.set_mode((width, height))
b_unit = 16
b = []
count = 0
cx = 0
cy = 0
while count < (width * height) / (b_unit * b_unit):
b.append(block(random.choice(materials), b_unit * cx, b_unit * cy))
cx += 1
count += 1
if cx == width / b_unit:
cx = 0
cy += 1
while True:
for block in b:
screen.blit(block.texture, (block.x + viewx, block.y + viewy))
pygame.display.flip()

I've already mentioned in the comments that you should (almost) always convert your images to improve the performance.
It can also help to blit separate images/pygame.Surfaces onto a big background surface and then just blit this background once per frame. I use two nested for loops here to get the coordinates and randomly blit one of two images.
I get around 120 fps if I use separate sprites (5184) here and ~430 fps with this single background image.
Of course I'm just blitting here and in a real game you'd probably have to store the rects of the tiles in a list or use pygame sprites and sprite groups, for example to implement collision detection or other map related logic, so the frame rate would be lower.
import itertools
import pygame as pg
from pygame.math import Vector2
BLUE_IMAGE = pg.Surface((20, 20))
BLUE_IMAGE.fill(pg.Color('lightskyblue2'))
GRAY_IMAGE = pg.Surface((20, 20))
GRAY_IMAGE.fill(pg.Color('slategray4'))
def main():
screen = pg.display.set_mode((1920, 1080))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
images = itertools.cycle((BLUE_IMAGE, GRAY_IMAGE))
background = pg.Surface(screen.get_size())
# Use two nested for loops to get the coordinates.
for y in range(screen.get_height()//20):
for x in range(screen.get_width()//20):
# This alternates between the blue and gray image.
image = next(images)
# Blit one image after the other at their respective coords.
background.blit(image, (x*20, y*20))
next(images)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# Now you can just blit the background image once
# instead of blitting thousands of separate images.
screen.blit(background, (0, 0))
pg.display.set_caption(str(clock.get_fps()))
pg.display.flip()
clock.tick(1000)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
Side notes: Don't add your images to the pygame.image module (that makes no sense at all).
material = pygame.image
material.grass = pygame.image.load("textures/grass.png")
Writing several statements in the same row separated with semicolons is really ugly and makes code less readable.
white = (255,255,255);(width, height) = (2048, 1008)

Related

Python + Pyglet: Efficiently updating the image used by a sprite

As the title says. Using batch drawing I get really good performance, even with 4096 sprites. However, since my sprites need to change their underlying image I run into issues with performance. I'm pretty sure I'm doing something silly here, since I specifically created a grid/sprite sheet to handle this effectively. But, of course, I never really use it in any effective manner. I might as well have had 5 different images.
What I really want is to keep the underlying sprite image constant, but shift the visible part based on the "food" metric. Here's the code:
import sys, pyglet, random, time
# Constants.
WIDTH = 1280
HEIGHT = 960
TARGET_FPS = 60
GROWTH_CHANCE = 0.1
fps = 0
screen = pyglet.window.Window(WIDTH, HEIGHT)
random.seed(time.time())
# Here we load universal assets, images, sounds, etc.
grass_tiles_img = pyglet.image.load('grass_tiles.png')
grass_tiles_grid = pyglet.image.ImageGrid(grass_tiles_img, 1, 5)
# Sprite batches.
grass_batch = pyglet.graphics.Batch()
class GrassTile:
'''Define a grass tile which cows can graze on.'''
def __init__(self, x, y, food):
self.food = food
self.sprite = pyglet.sprite.Sprite(grass_tiles_grid[0], x, y,
batch=grass_batch)
def draw(self):
grid_index = (self.food // 20)
self.sprite.image = grass_tiles_grid[grid_index]
return self.sprite
def grow(self):
if random.random() < GROWTH_CHANCE:
self.food = min(self.food + 1, 99)
#screen.event
def on_close():
sys.exit()
#screen.event
def on_draw():
# Clear the screen.
screen.clear()
# Draw grass.
grass_sprites = []
for grass in grass_tiles:
grass_sprites.append(grass.draw())
grass_batch.draw()
# Draw FPS counter.
label = pyglet.text.Label('FPS: ' + str(fps), 'Times New Roman', 12, 10, 10)
label.draw()
def grow_grass(dt):
for grass in grass_tiles:
grass.grow()
def calculate_fps(dt):
global fps
fps = round(min(pyglet.clock.get_fps(), TARGET_FPS))
grass_tiles = [GrassTile(20 * i, 15 * j, 0) for j in range(64) for i in range(64)]
pyglet.clock.schedule_interval(grow_grass, 1 / TARGET_FPS)
pyglet.clock.schedule_interval(calculate_fps, 1 / TARGET_FPS)
pyglet.app.run()
And here's the image so you can run the code:
https://i.imgur.com/kFe91aA.png
Why not just have the image change during grass.grow()?
You don't need to do anything to the grass in the draw phase except draw the batch. Setting the image of a sprite isn't a draw operation, it just changes texture coordinates.
def grow(self):
if random.random() < GROWTH_CHANCE:
self.food = min(self.food + 1, 99)
grid_index = (self.food // 20)
self.sprite.image = grass_tiles_grid[grid_index]
You also shouldn't be recreating the label every draw frame. Create the label beforehand and just update the text. label.text = f'FPS: {fps}'

Surface display able to properly represent opacity, but any other surface cannot

I am trying to make a tic-tac-toe game with pygame. An important thing I want is being able to make my images (eg. X and O) slightly translucent for when my user is only hovering over a grid tile. I also use opacity to visually show whose turn it is.
This is what I have tried:
x_tile = pygame.image.load('x_tile').convert()
x_tile.set_alpha(100)
This works fine when I'm blitting x_tile directly onto the display like this:
# This is for simplicity's sake. The actual blit process is all being done in an infinite loop
screen = pygame.display.set_mode((300, 300))
screen.blit(x_file, x_file.get_rect())
But my game is using another image that represents the grid, and that is what I'm blitting onto. So I'm blitting this board onto the display, then blitting the actual X and O tiles on the board.
screen = pygame.display.set_mode((300, 300))
screen.blit(board, board_rect)
board.blit(x_tile, x_tile.get_rect(center=grid[0].center)) # I have a list of Rects that make a grid on the board image. grid[0] is the top left
When I do it that way, x_tile.set_alpha(100) seems to have no effect and I don't know what to do.
Edit: I am using pygame 2.0.1. I'm on Windows 10.
Here is the entire code
import os
import pygame
from pygame.locals import *
# Game constants
WIN_SIZE = WIN_WIDTH, WIN_HEIGHT = 800, 600
BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
BLUE = 0, 0, 255
# Game functions
class NoneSound:
"""dummy class for when pygame.mixer did not init
and there is no sound available"""
def play(self): pass
def load_sound(file):
"""loads a sound file, prepares it for play"""
if not pygame.mixer:
return NoneSound()
music_to_load = os.path.join('sounds', file)
try:
sound = pygame.mixer.Sound(music_to_load)
except pygame.error as message:
print('Cannot load following sound:', music_to_load)
raise SystemExit(message)
return sound
def load_image(file, colorkey=None, size=None):
"""loads image into game"""
image_to_load = os.path.join('images', file)
try:
image = pygame.image.load(image_to_load).convert()
except pygame.error as message:
print('Cannot load following image:', image_to_load)
raise SystemExit(message)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
if size is not None:
image = pygame.transform.scale(image, size)
return image
# Game class
class TTTVisual:
"""Controls game visuals"""
def __init__(self, win: pygame.Surface):
self.win = win
# Load in game images
self.board = load_image('board.png', size=(600, 450), colorkey=WHITE)
self.x_tile = load_image('X_tile.png', size=(100, 100), colorkey=BLACK)
self.o_tile = load_image('O_tile.png', size=(100, 100), colorkey=BLACK)
# Translucent for disabled looking tile
self.x_tile_trans = self.x_tile.copy()
self.o_tile_trans = self.o_tile.copy()
self.x_tile_trans.set_alpha(100)
self.o_tile_trans.set_alpha(100)
# Used to let user know whose turn it is
self.x_turn = pygame.transform.scale(self.x_tile, (50, 50))
self.o_turn = pygame.transform.scale(self.o_tile, (50, 50))
self.x_turn_trans = pygame.transform.scale(self.x_tile_trans, (50, 50))
self.o_turn_trans = pygame.transform.scale(self.o_tile_trans, (50, 50))
self.get_rects()
self.grid = self.setup_grid()
def get_rects(self):
"""Creates coords for some visual game assets"""
self.board_rect = self.board.get_rect(
center=self.win.get_rect().center)
self.x_turn_rect = self.x_turn.get_rect(top=10, left=10)
self.o_turn_rect = self.o_turn.get_rect(top=10, left=WIN_WIDTH-60)
def setup_grid(self):
grid = []
left = 0
top = 150
row = 0
for i in range(9):
if (i != 0) and (i % 3 == 0):
row += 1
left = 0
grid.append(pygame.Rect(left, row*top, 200, 150))
left += 200
return grid
def update_turn_status(self):
"""Updates the X and O tiles on the top left and right to
let user know whose turn it is"""
self.win.blits((
(self.x_turn_trans, self.x_turn_rect),
(self.o_turn, self.o_turn_rect)
))
def update_grid(self):
"""Updates board"""
self.win.blit(self.board, self.board_rect)
# Here is where you could change board to win and see that the tile changes in opacity
self.board.blit(self.x_tile_trans, self.x_tile_trans.get_rect(center=self.grid[0].center))
def update(self):
self.win.fill(WHITE)
self.update_turn_status()
self.update_grid()
pygame.display.flip()
def main():
pygame.init()
win = pygame.display.set_mode(WIN_SIZE)
tttvisual = TTTVisual(win)
tttfunc = TTTFunc(tttvisual)
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
running = False
tttvisual.update()
pygame.quit()
if __name__ == "__main__":
main()
The issue is caused by the line:
self.board.blit(self.x_tile_trans, self.x_tile_trans.get_rect(center=self.grid[0].center))
You don't blit the image on the display Surface, but on the self.board Surface. When a Surface is blit, it is blended with the target. When you draw on a Surface, it changes permanently. Since you do that over and over again, in every frame, the source Surface appears to by opaque. When you decrease the alpha value (e.g. self.x_tile_trans.set_alpha(5)), a fade in effect will appear.
Never draw on an image Surface. Always draw on the display Surface. Cleat the display at begin of a frame. Draw the entire scene in each frame and update the display once at the end of the frame.
class TTTVisual:
# [...]
def update_grid(self):
"""Updates board"""
self.win.blit(self.board, self.board_rect)
# Here is where you could change board to win and see that the tile changes in opacity
x, y = self.grid[0].center
x += self.board_rect.x
y += self.board_rect.y
self.win.blit(self.x_tile_trans, self.x_tile_trans.get_rect(center=(x, y)))
The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()

Several screens "overlapping" pygame

I started today to program a game with pygame. In the background is a kind of grid on which you will play in the future. But I noticed that with a while loop to update the screen, the grid is redrawn every time and that's a waste of resources, because nothing changes there anyway. Now I thought about not updating the grid-screen in the background and creating a new screen to play on, which will be updated. But then I encountered a problem: When pygame starts a new screen, the last one closes.
So is it smart to have the game board redrawn every time or is there another method where you can leave an item in the background without updating it? Thank you very much for any help. Code and (wrong) approaches follow.
main.py
import field, game
import ctypes
# Variables
def main():
width, height = ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1)
width_scale, height_scale = 5 / 10, 9 / 10
black = (0, 0, 0)
white = (255, 255, 255)
background_color = (214, 237, 255)
refresh_rate = 60
field_size = [10, 18]
screen = pg.display.set_mode([int(width * width_scale), int(height * height_scale)], pg.NOFRAME)
while True:
for event in pg.event.get():
if event.type == pg.KEYDOWN:
pass
screen.fill(background_color)
box_size = field.draw_boxes(screen.get_width(), screen.get_height(), field_size, screen)
field.draw_next_hand()
pg.display.flip()
game.main(width, height, box_size, field_size)
if __name__ == '__main__':
main()
pg.quit()
field.py
import pygame as pg
def draw_boxes(w, h, size, screen):
global start_x, box_size, g_screen, grey, s
g_screen = screen
s = size
box_size = int(w / 2 / (size[0]+1))
start_x = int(w / 2 - size[0] / 2 * box_size)
grey = (122, 122, 122)
for column in range(0, size[0], 1):
for row in range(0, size[1], 1):
pg.draw.rect(screen, grey, [start_x + column * box_size, box_size + row * box_size, box_size, box_size], width= 1)
return box_size
def draw_next_hand():
global box_size, start_x, g_screen, grey
next_hand_size = 4
next_hand_distance = 1
for column in range(0, next_hand_size, 1):
for row in range(0, next_hand_size, 1):
pg.draw.rect(g_screen, grey, [start_x - 2*box_size*next_hand_distance - column * box_size, box_size + row * box_size, box_size, box_size], width=1)
pg.draw.rect(g_screen, grey, [start_x + box_size*s[0] + box_size * next_hand_distance + column * box_size, box_size + row * box_size, box_size, box_size], width=1)
game.py
import pygame as pg
from main import main
def main(width, height, box_size, f_size):
# Variables
white = (255, 255, 255)
black = (0, 0, 0)
grey = (122, 122, 122)
refresh_rate = 60
g_screen = pg.display.set_mode([int(f_size[0] * box_size), int(f_size[1] * box_size)], pg.NOFRAME)
while True:
g_screen.fill(white)
pg.display.flip()
pg.time.delay(refresh_rate)
Before I added the new screen I had "pg.time.delay(refresh_rate)" instead of "game.main()", which caused the background to be constantly redrawn, so I tried to draw another screen over it, which of course didn't work^^
I've already found some entries on stack overflow, but they didn't fit my problem, because it was suggested to change the screen with for example main = False and game = True, but this wouldn't prevent the board from being redrawn
There's a few ways to improve the performance concerning the background image.
Draw once - You can store the background image in a surface object so it only needs to be generated once. Pygame will retain the screen when hidden or minimized.
Only redraw the updated section - Set a clipping rectangle on the screen so only certain pixels get refreshed when the background is redrawn
Only redraw when needed - The game loop is required, but you can conditionally re-render the background
Draw efficiently - Slow down the game loop using the pygame.time.Clock().tick() method
Here's a short program that illustrates these points. It just shows the current date\time on a background of circles.
import pygame as pg
import time
from datetime import datetime as dt
from random import randint
WIDTH = 480
HEIGHT = 600
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
def rnd(rg): # save some typing
return randint(0,rg)
font_name = pg.font.match_font('arial')
def draw_text(surf, text, size, x, y): # draw text on screen in rect
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, (rnd(255),rnd(255),rnd(255)))
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def make_bg(): # create background image
surf_bg = pg.Surface((WIDTH, HEIGHT))
surf_bg.fill((0,0,0)) # start with black
for i in range(500): # 500 circles
pg.draw.circle(surf_bg,(rnd(255),rnd(255),rnd(255)), (rnd(WIDTH),rnd(HEIGHT)), 15+rnd(50))
return surf_bg
surf_bg = make_bg() # generate circles once, store surface object
#initial background
screen.blit(surf_bg, screen.get_rect()) # draw background, only needed once in Windows
screen.set_clip((10, HEIGHT/2 - 20, WIDTH-10, HEIGHT/2 + 20)) # set active region on screen
lasttick = pg.time.get_ticks() # milliseconds since init
while True:
pg.time.Clock().tick(5) # run loop 5 times per second
pg.event.get() # required in Windows for OS events
if pg.key.get_pressed()[pg.K_SPACE]: quit() # press space to quit
if (pg.time.get_ticks() - lasttick < 1000): continue # only redraw time each second
lasttick = pg.time.get_ticks()
screen.blit(surf_bg, screen.get_rect()) # background, update clip region only
draw_text(screen, str(dt.now()), 30, WIDTH / 2, HEIGHT / 2 - 10) # draw time
pg.display.flip() # swap screen buffer

Pygame pixel perfect collision not working as expected

I am creating tetris using pygame. i want to use collision detection so that when the shape in play comes into contact with any other previously played shapes, i can stop the shape, as per the logic of tetris. i came across pixel perfect collision using masks. i have followed some tutorials online, however the pixel detection returns true every time a new shape comes into play, not when any shapes collide. sorry in advance for the long code, its the bare minimum for the code to actually and still containing the game element of it. i think there is something wrong with my approach which is causing this error. I basically have a function that everytime the shape in play comes into contact with the 'floor' that shape is held in that position and a new shape is created. i think ive overcomplicated it, in turn creating this error. thanks in advance
import pygame
import sys
import shapelogic
pygame.init()
screensize = width, height = 800, 595
screen = pygame.display.set_mode(screensize)
background_image =pygame.image.load("/Users/marceason/PycharmProjects/Tetris/Wooden_background.jpg").convert_alpha()
myshape = 0
stop_movement = 0
blit_count = 0
stored_shapes = pygame.sprite.Group()
stored_shapes_with_coords = []
extra_blit_required = False
index = 0
count = 0
listofshapes = []
class shapemanager():
def __init__(self):
self.listofshapes = []
def create_another_instance(self):
global count
count += 1
string = "Shape_{0},".format(count)
another_shape = Shape(string)
self.listofshapes.append(another_shape)
global index
object = self.listofshapes[index]
index += 1
return object
def load_shape(self):
shape = self.create_another_instance()
shape.load_shapes()
class Shape(pygame.sprite.Sprite):
def __init__(self, name):
pygame.sprite.Sprite.__init__(self)
self.name = name
self.x = 50
self.y = 100
self.move_event = pygame.USEREVENT + 1
self.reached_bottom_event = pygame.USEREVENT + 2
self.one_sec_timer = 1000
self.half_sec_timer = 500
self.reachbottomflag = False
self.movement_possible = True
self.image = pygame.image.load(
"/Users/marceason/PycharmProjects/Tetris/Tetris_Shapes/Green_Shape_1_Position_1.png")
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
def move_shape(self):
if self.movement_possible:
key_input = pygame.key.get_pressed()
if key_input[pygame.K_LEFT]:
self.x -= 16
if key_input[pygame.K_RIGHT]:
self.x += 16
if not self.reachbottomflag:
if key_input[pygame.K_DOWN]:
self.y += 16
def reachbottom(self):
if self.y >= 560:
self.reachbottomflag = True
def no_movement_possible(self):
self.movement_possible = False
def assign_shape():
global myshape
global stop_movement
myshape = sl.create_another_instance()
pygame.time.set_timer(myshape.move_event, myshape.one_sec_timer)
stop_movement = pygame.time.set_timer(myshape.reached_bottom_event, myshape.half_sec_timer)
def blit_used_shapes():
global screen
global blit_count
blit_count = len(stored_shapes_with_coords)
local_count = 0
while local_count < blit_count:
screen.blit(stored_shapes_with_coords[local_count][0], (stored_shapes_with_coords[local_count][1], stored_shapes_with_coords[local_count][2]))
local_count += 1
sl = shapemanager()
##### HERE IS THE PIXEL DETECTION #####
result = pygame.sprite.spritecollide(myshape, stored_shapes, False, pygame.sprite.collide_mask)
## Main loop ##
assign_shape()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
screen.blit(background_image, (0, 0))
screen.blit(myshape.image, (myshape.x, myshape.y))
myshape.move_shape()
key_input = pygame.key.get_pressed()
if key_input[pygame.K_SPACE]:
myshape.rotate_shape()
myshape.reachbottom()
if myshape.reachbottomflag:
if event.type == myshape.reached_bottom_event:
myshape.no_movement_possible()
stored_shape_tuple = [myshape.image, myshape.x, myshape.y]
stored_shapes_with_coords.append(stored_shape_tuple)
stored_shapes.add(myshape)
extra_blit_required = True
assign_shape()
####### PIXEL DETECTION IS HERE IN FOR LOOP ####
if result:
print("this should only execute when two shapes touch!!")
if extra_blit_required:
blit_used_shapes()
pygame.display.update()
The issue is that you are not updating the sprites rect attribute. The sprites rects all have position (0, 0) (since you do not set it in the call to self.image.get_rect()) and as a result the masks will all overlap and collide.
If you read the docs for pygame.sprite.collide_mask you will note that it says that your sprites need to have mask and rect attributes. You have a rect in your sprite and you set it in the __init__(), but you do not keep it updated when you move the sprite. You just change the x and y attributes without adjusting the rect position. The reason that the collide_mask wants a rect is that it uses that to determine the offset parameter for the pygame.mask.Mask.overlap() call that it uses. The important thing to realize is that masks themselves do not have a position, they need the rects to determine the relative positions of the masks.
This is similar to images/surfaces not having a position and needing a rect to track that for them.
On a separate issue, the way you are blit'ing the sprites to the screen makes no sense. You are not using the abilities of the sprite groups to draw and worse you are keeping the image, x and y of the sprite in a separate list and not containing it in the sprite itself. You should go look at some examples of pygame sprite based code. There are lots of examples out there.

problem with making background of image transparent: pygame

I'm in the middle of working on a simple typing tutor using pygame. My problem is that I'm using an image that has a white background, waves1.png. Now's I've specified that I want white to be transparent in the image (self.image.set_colorkey((255, 255, 255))) and it is for everything except the text block. When the waves intersect with the text object, the white background of the waves show on top of the text. You can try running this if you have pygame (with the exception of the waves1.png image).
import pygame
from pygame.locals import *
class TextSprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.wordList = ['words yes', 'hello', 'this is a sentence', 'this is another sentence'] # read directly from external file
self.pos = 0
self.wordNum = 0
self.update1()
def update1(self):
# Render the given word
self.image = pygame.font.Font(None, 36).render(self.wordList[self.wordNum], 1, (0, 0, 0))
# Render the correctly guessed letters
self.correct = pygame.font.Font(None, 36).render(self.wordList[self.wordNum][:self.pos], 1, (255, 0, 0))
# Copy correct letters onto given word
self.image.blit(self.correct, (0, 0))
self.rect = self.image.get_rect()
# set the center of the center the given word to the center of the screen
self.rect.center = pygame.display.get_surface().get_rect().center
def keyin(self, key):
word = self.wordList[self.wordNum]
letter = word[self.pos]
if letter == key:
self.pos = self.pos + 1
if self.pos == len(word):
self.reset()
self.update1()
def reset(self):
self.pos = 0
self.wordNum = self.wordNum + 1
self.update1()
class Waves(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, filename):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.image.load(filename).convert()
# makes any white in the image transparent
self.image.set_colorkey((255, 255, 255))
self.rect = self.image.get_rect()
# Decrease the y coordinate so the waves look like they're moving up
def update(self, text):
self.rect.y = self.rect.y - 6
if self.rect.y <= 200:
text.reset()
self.rect.y = 485
def main():
#I - Import and initialize
pygame.init()
#D - Display configuration
# The screen variable is a pygame Surface object
# Note that the set_mode() method creates a Surface object for you automatically
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Typing Game")
#E - Entities (just background for now)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255, 255, 255))
screen.blit(background, (0,0))
#A - Action (broken into ALTER steps)
#A - Assign values to key variables
clock = pygame.time.Clock()
keepGoing = True
# Collect the sprite in a list
all = pygame.sprite.RenderPlain()
waveList = pygame.sprite.RenderPlain()
text = TextSprite()
all.add(text)
waves = Waves("waves1.png")
waveList.add(waves)
waves.rect.x = 0
waves.rect.y = 485
#L - Set up main loop
while keepGoing:
#T - Timer to set frame rate
# Tick is a method in the Clock class that determines the maximum frame rate
clock.tick(30)
#E - Event handling
for event in pygame.event.get():
if event.type == QUIT:
keepGoing = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
keepGoing = False
else:
text.keyin(event.unicode)
# update position of waves
waves.update(text)
# clears screen
all.clear(screen, background)
# update screen
all.draw(screen)
waveList.clear(screen, background)
waveList.draw(screen)
# display.flip is a method that copies everything from the screen object to the actual visual display
pygame.display.flip()
pygame.quit ()
if __name__ == '__main__': main()
I don't know if it's an option for you, but you should get better results with png's native alpha transparency.
If you can edit/recreate the png yourself, then try using a transparent background.
From there, you can use convert_alpha() arfter loading the image. (instead of using a colorkey)
http://pygame.org/docs/ref/surface.html#Surface.convert_alpha
EDIT: one other aspect, is that the image may have an alpha channel interfering with the colorkey. Best to ensure you're not trying to use both.
I'm told that you can detect an image's alpha channel programmatically. Something like ...
if self.image.get_masks()[3]!=0:
print "image has alpha!"
See here http://pygame.org/docs/ref/surface.html#Surface.get_masks
HTH
Well done! You've actually done everything correctly to take advantage of transparency and colorkey (ie, making sure to call convert on the surface, making sure to pass the color into the set_colorkey method, etc).
The problem is with the order of calls to draw and clear on your respective sprite groups, "all" and "waveList". After you've rendered the text blocks by calling all.draw, you then follow it with the call to waveList.clear.
Here's the problem: once you've drawn the text sprites, you don't want to clear the space underneath the wave sprites, or that will wipe out the area that overlaps the already-drawn text blocks.
If you want to do this properly, try doing it in this order:
waves.update()
all.clear(screen,background)
waveList.clear(screen,background)
all.draw(screen)
waveList.draw(screen)
(more simply, just move waveList.clear(screen, background) to the line just below all.clear(screen, background); that should do it)
When I'm working with sprite groups, I usually try to group it so that each sprite group calls the same method in this order: clears, updates, collision checks (if any), draws.
This usually handles things in the right order. Then you still may have to pay attention to whether there is any layering of sprites, but that's another story for another day.

Categories

Resources