I have a rather confusing problem. I currently have a countdown and I would ideally have the text from the countdown to be somewhat transparent (say 50% or so)
pygame.init()
surface = pygame.display.set_mode((0,0))
fontObj = pygame.font.Font('freesansbold.ttf', 600)
textSurfaceObj = fontObj.render("3", True, (255, 255, 255))
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (surface.get_width() / 2, surface.get_height() / 2)
pygame.mouse.set_visible(False)
while True:
surface.fill(255, 255, 255)
pygame.display.update()
time = str(datetime.datetime.now())
filename = 'photos/' + time.replace(' ', '_') + '.jpg'
for i in xrange(3, 0, -1):
surface.fill(WHITE)
textSurfaceObj = fontObj.render(str(i), True, (255, 0, 0)
surface.blit(textSurfaceObj, textRectObj)
pygame.display.update()
pygame.time.wait(1000)
pygame.display.update()
pygame.time.wait(100);
surface.fill(WHITE)
pygame.display.update()
I've tried putting in surface.set_alpha(50) but that doesnt seem to do anything. Any suggestions are very welcome!
In pygame you must set a background color for antialiased text if you want it to use a color key (which allows you to render transparent text). To get the result you want you just need to match the background color to the surface color, in this case white. The below code (starting right after the for i in ...) worked for me:
surface.fill(WHITE)
textSurfaceObj = fontObj.render(str(i), True, (255, 0, 0),WHITE)
textSurfaceObj.set_alpha(50)
surface.blit(textSurfaceObj,(0,0))
pygame.display.update()
pygame.time.wait(500)
Edit: I did a little digging as to what's going on here, and this mailing list post details the backend properties that cause this for anyone interested.
Related
i have a code that pops up a speechbubble when the player hits a rectangle. But now its just spamming the speech bubble. Thats not good because i have random texts that appears so it's just going through it very fast
this is the code for the speech bubble
def draw_speech_bubble(screen, text, text_color, bg_color, pos, size):
font = pygame.font.SysFont(None, size)
text_surface = font.render(text, True, text_color)
text_rect = text_surface.get_rect(midbottom=pos)
#Background Object
bg_rect = text_rect.copy()
bg_rect.inflate_ip(10,10)
#Border
border_rect = bg_rect.copy()
border_rect.inflate_ip(4,4)
pygame.draw.rect(screen, text_color, border_rect)
pygame.draw.rect(screen, bg_color, bg_rect)
screen.blit(text_surface, text_rect)
This is my code for the collision
if(player.player_rect.colliderect(BarCounter)):
draw_speech_bubble(screen, str(RandomText()), (255, 255, 255), (0, 0,0),SpeechBubbleAnchor.midtop,25)
I want some sort of cooldown so it doesn't spam the speechbubbles. I tried making a calculation with ticks but i wasn't able to do that
Add a variable that stores the text (current_bubble_text) and change the text when the player hits the rectangle. Use pygame.time.get_ticks() to get the number of milliseconds since pygame.init() was called. Calculate the point in time at which the text has to disappear again. When the time comes, reset the variable:
current_bubble_text = None
bubble_text_end_time = 0
#application loop
while True:
current_time = pygame.time.get_ticks()
# [...]
if current_bubble_text == None and player.player_rect.colliderect(BarCounter):
current_bubble_text = RandomText()
bubble_text_end_time = current_time + 5000 # 1 second time interval
if current_bubble_text:
draw_speech_bubble(screen, current_bubble_text,
(255, 255, 255), (0, 0, 0), SpeechBubbleAnchor.midtop, 25)
if current_time > bubble_text_end_time:
current_bubble_text = None
# [...]
See also Adding a particle effect to my clicker game.
i wanted to draw a circle in pygame that is empty, i mean you should see behind surface through it.
i wrote a code that find all the colored pixels in a surface and empty their coordinates in the other surface.
def draw_empty(surf1, surf2, pos):
"""makes surf2 pixels empty on surf1"""
pixobj2 = pygame.PixelArray(surf2)
empty = []
for x in range(len(pixobj2)):
for y in range(len(pixobj2[x])):
if pixobj2[x][y]!=0:
empty.append((x,y))
del pixobj2
pixobj1 = pygame.PixelArray(surf1)
for pix in empty:
pixobj1[pix[0]+pos[0]][pix[1]+pos[1]] = 0
del pixobj1
window = pygame.display.set_mode((600, 600))
white_surf = pygame.surface.Surface((600, 600))
white_surf.fill((255, 255, 255))
circle_surf = pygame.surface.Surface((50, 50))
pygame.draw.circle(circle_surf, (1, 1, 1), circle_surf.get_rect().center, 25)
pic = pygame.image.load('pic.png')
pic = pygame.transform.scale(pic, (600, 600))
done = False
while not done:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
draw_empty(white_surf, circle_surf, (200, 200))
window.blit(pic, (0, 0))
window.blit(white_surf, (0, 0))
pygame.display.update()
pygame.time.Clock().tick(60)
i expected to see background picture through that circle but the circle i just black, is this even possible to do that? can somebody help me with this?
P.S.
by empty, i mean like a hole in my front surface
Just use the draw() function:
pygame.draw.circle(Surface, color, pos, radius, width=0)
width represents the size of the circumference curve. When it is 0, the circle is solid. If you set it to 1, the edge will be only one pixel wide (an empty circle).
edit: to draw a circle with a sprite, you can use this code†:
import pygame
import pygame.gfxdraw
IMG = pygame.Surface((30, 30), pygame.SRCALPHA)
pygame.gfxdraw.aacircle(IMG, 15, 15, 14, (0, 255, 0))
pygame.gfxdraw.filled_circle(IMG, 15, 15, 14, (0, 255, 0))
class img(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = IMG
self.rect = self.image.get_rect(center=(150, 200))
†Credit for code goes to dunker_wanderer
You can draw the shape the same way you would if it had a color or surface image, and then just set the fill to a transparent color using:
empty = (255,255,255,0)
surface.fill(empty)
You will have to figure out how to add this to your code without breaking it, or rewrite it but, first you will need to make a set with three numbers
white = (255, 255, 255)
next use the function
pygame.draw.rect(canvas_name, set_name, (100, 100, 100, 100))
last use
pygame.display.flip()
#Initializes pygame import pygame, random, sys, time, math pygame.init()
#Creates screen screen = pygame.display.set_mode((400, 350)) pygame.display.set_caption("Game")
#Initializes screen running = True while running: pass
#Colors screen white = (255, 255, 255) screen.fill(white)
#Draws rectangle num1 = random.randrange(0, 255) num2 = random.randrange(0, 255) num3 = random.randrange(0, 255)
color = (num1, num2, num3) pygame.draw.rect(screen, color, pygame.Rect(100, 100, 60, 60), )
pygame.display.flip()
#Made by and only by the kid genius Nathan
Something that looks like this but I want the image and text editable.
Instead of having something like:
title = menuFont.render("COMPUTER INFORMATION!", 1, BLACK)
screen.blit(title, Rect(50, 100, 400, 400))
Is it possible for the colour in the text to be an image instead, or an animation?
EDIT:
For those curious... when I imported the imaged, I had to change the end of the code a bit
screen.blit(texture, (50, 50))
screen.fill(BG_COLOR)
screen.blit(text_surface, (50, 170))
pg.display.update()
clock.tick(30)
The screen.fill comes after the texture... just a heads up :)
To texture your text, you can first render the text in white, then blit the texture onto it and pass pygame.BLEND_RGB_MULT as the special_flags argument to use the multiply blend mode. The texture will appear only on the opaque parts of the text surface.
Also, make sure that your texture is bigger than the text surface, otherwise some parts of the text will remain unaffected.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray32')
FONT = pg.font.Font(None, 50)
# I create a grid texture for demonstration purposes here.
# Just load your image with pygame.image.load instead.
texture = pg.Surface((200, 100))
texture.fill((200, 100, 0))
for x in range(0, 201, 5):
pg.draw.line(texture, (0, 0, 0), (x, 0), (x, 200))
for y in range(0, 101, 5):
pg.draw.line(texture, (0, 0, 0), (0, y), (200, y))
# Render the text and use pure white as the color.
text_surface = FONT.render('Hello world!', True, (255, 255, 255))
# Now blit the texture onto the text surface and pass BLEND_RGB_MULT as
# the special_flags argument, so that only the opaque parts are affected.
text_surface.blit(texture, (0, 0), special_flags=pg.BLEND_RGB_MULT)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
screen.fill(BG_COLOR)
screen.blit(texture, (50, 50))
screen.blit(text_surface, (50, 170))
pg.display.flip()
clock.tick(30)
pg.quit()
Here's the animated version. You have to load the separate frames of the animation and do the same as above for each frame. Put the resulting surfaces into a list and then play them back in the main loop.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray32')
FONT = pg.font.Font(None, 50)
# I create a grid texture for demonstration purposes here.
# Just load your image with pygame.image.load instead.
texture = pg.Surface((200, 100))
texture.fill((200, 100, 0))
for x in range(0, 201, 5):
pg.draw.line(texture, (0, 0, 0), (x, 0), (x, 200))
for y in range(0, 101, 5):
pg.draw.line(texture, (0, 0, 0), (0, y), (200, y))
# Render the text and use pure white as the color.
text_surface = FONT.render('Hello world!', True, (255, 255, 255))
frames = []
for i in range(5):
surf = text_surface.copy() # We need a fresh copy of the text.
# Now blit the texture onto the text surface and pass BLEND_RGB_MULT as
# the special_flags argument, so that only the opaque parts are affected.
# The y-position is shifted by -1 each iteration.
surf.blit(texture, (0, -1*i), special_flags=pg.BLEND_RGB_MULT)
frames.append(surf)
frame_counter = 0
frame_timer = 0
dt = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
frame_timer += dt # Add the passed time.
if frame_timer >= 150: # If 150 milliseconds have passed...
frame_timer = 0 # Reset the timer.
frame_counter += 1 # Increment the counter.
frame_counter %= len(frames) # Keep it in the correct range.
screen.fill(BG_COLOR)
# Now use `frame_counter` as the list index and blit the surface.
screen.blit(frames[frame_counter], (50, 170))
pg.display.flip()
dt = clock.tick(60) # `dt` is the passed time in milliseconds.
pg.quit()
So, I'm following a tutorial which currently has me building the following for a quick look at drawing using pygame functions.
import pygame, sys
from pygame.locals import *
pygame.init() #has to be called before any other pygame functions
#setup the window
DISPLAYSURF = pygame.display.set_mode((500,400), 0, 32)
pygame.display.set_caption('Drawing')
#colors
black = (0, 0, 0, 0)
white = (255, 255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
BLUE = (0, 0, 255)
#draw on the surface object
DISPLAYSURF.fill(white)
pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(DISPLAYSURF, BLUE,(120,60), (60,120))
pygame.draw.line(DISPLAYSURF, BLUE,(60,120), (120,120), 4)
pygame.draw.circle(DISPLAYSURF, BLUE, (300,500), 20, 0)
pygame.draw.ellipse(DISPLAYSURF, red, (300, 250, 40, 80), 1)
pygame.draw.rect(DISPLAYSURF, red, (200,150,100,50))
pixObj = pygame.pixelarray(DISPLAYSURF)
pixObj[480][380] = black
pixObj[482][382] = black
pixObj[484][384] = black
pixObj[486][386] = black
pixObj[488][388] = black
del pixObj
#run game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
My problem is that in attempting to run this code, I get an invalid syntax error pointing to the first pygame.draw.line. If this is somehow a typo, I'll be kinda surprised, I retyped those lines several times to make sure they were correct, even double checked the docs to make sure that was still the valid syntax. Any ideas?
Focusing on that line:
pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))
Let's make some changes to it, that take valid syntax to valid syntax.
pygame.draw.polygon(DISPLAYSURF, green, ((), (), (), (), ())
pygame.draw.polygon(DISPLAYSURF, green, ()
pygame.draw.polygon(
There are more open parentheses than closing.
If the following lines are correct, you should remove an open paren after "green".
So I fell against this weird problem where I can't fill the screen. My code is
#Import all modules
import pygame
import random
import math
import time
#Colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
ORANGe = (255, 115, 0)
YELLOW = (242, 255, 0)
BROWN = (115, 87, 39)
PURPLE = ( 298, 0, 246)
GRAY = ( 168, 168, 168)
BLUE = ( 0, 0, 255)
pygame.init()
# Clock
clock = pygame.time.Clock()
#Screen
screenx = 1000
screeny = 700
screen = pygame.display.set_mode([screenx,screeny])
#Title
pygame.display.set_caption("OUCH Version 0.1")
#Classes (if any)
#Variables
sound = True
password = False
titlescreen = True
#Booleans
#Sounds
#The graphics
#Positions
#Time management
fps = 60
#Other Things
#Main Loop__________________________________________________
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if titlescreen:
screen.fill(WHITE)
#Flip the Display
pygame.display.flip
clock.tick(fps)
#If done
pygame.quit()
I just updated to python 3.4, may that be the problem. Or am I overlooking something. I'm trying to fill the screen white but every time I run it the screen always turns out to be black. Thank you for any help. :)
What I have tried__________
I tried looking if theirs something with the color WHITE, but when I try any other color it does not work. I also tried just screen filling with ought the Boolean yet that doesn't work either. I have also tried not doing if titlescreen:, but if titlescreen == True: then bla bla
You forgot to put brakets:
pygame.display.flip()