How do I draw text onto the screen in pygame? - python

I'm trying to just draw any text on to the screen in pygame but when I run the program it just runs normally but no text appears on the screen. Is there something I'm doing wrong?
import pygame, random, sys
from pygame.locals import *
pygame.init()
#set constants
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 255)
FPS = 40
BLACK = (0,0,0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
#set variables
rectY1 = 200
rectY2 = 200
Y1change = 0
Y2change = 0
ballX = 320
ballY = 240
ballXvel = 0
ballYvel = 0
paddle1 = pygame.Rect(18,rectY1,10,100)
paddle2 = pygame.Rect(620,rectY2,10,100)
ball = pygame.Rect(ballX,ballY,30,30)
font = pygame.font.SysFont(None, 48)
#create shapes
def drawshapes():
pygame.draw.rect(DISPLAY, WHITE, paddle1)
pygame.draw.rect(DISPLAY, WHITE, paddle2)
pygame.draw.rect(DISPLAY, WHITE, ball)
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
#set up display
DISPLAY = pygame.display.set_mode((640,480),0,32)
pygame.display.set_caption('Pong')
fpsClock = pygame.time.Clock()
drawText('bruh', font, DISPLAY, (200), (200))
pygame.display.update

idk if this really is the loop you are talking about but here it is:
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 128 ))
#background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

Related

Why don't three R, G and B circles blend correctly?

I am trying to represent the RGB color model using python + pygame.
I wanted to get the following:
So then, I wrote the following code:
import pygame, sys
from pygame.locals import *
ALPHA = 100
TRANSPARENT = (255,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0,100)
GREEN = (0,255,0,100)
BLUE = (0,0,255,100)
pygame.init()
size=(800,500)
screen= pygame.display.set_mode(size)
surf1 = pygame.Surface(size)
surf1.fill(TRANSPARENT)
surf1.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf1, BLUE, (430, 280), 60 )
surf2 = pygame.Surface(size)
surf2.fill(TRANSPARENT)
surf2.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf2, GREEN, (370, 280), 60 )
surf3 = pygame.Surface(size)
surf3.fill(TRANSPARENT)
surf3.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf3, RED, (400, 220), 60 )
surf1.set_alpha(ALPHA)
surf2.set_alpha(ALPHA)
surf3.set_alpha(ALPHA)
while True :
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(surf1, (0,0))
screen.blit(surf2, (0,0))
screen.blit(surf3, (0,0))
pygame.display.flip()
But instead of getting the RGB color model, I got this, with colors incorrectly blended:
Does anybody know what it could be? Thanks!
This should work:
import pygame, sys
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0, 100)
GREEN = (0, 255, 0, 100)
BLUE = (0, 0, 255, 100)
pygame.init()
size = (800, 500)
screen = pygame.display.set_mode(size)
surf1 = pygame.Surface(size)
surf1.fill(BLACK)
surf1.set_colorkey(BLACK)
pygame.draw.circle(surf1, BLUE, (430, 280), 60)
surf2 = pygame.Surface(size)
surf2.fill(BLACK)
surf2.set_colorkey(BLACK)
pygame.draw.circle(surf2, GREEN, (370, 280), 60)
surf3 = pygame.Surface(size)
surf3.fill(BLACK)
surf3.set_colorkey(BLACK)
pygame.draw.circle(surf3, RED, (400, 220), 60)
surf4 = pygame.Surface(size)
surf4.set_colorkey(BLACK)
surf4.blit(surf1, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
surf4.blit(surf2, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
surf4.blit(surf3, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(WHITE)
screen.blit(surf4, (0, 0))
pygame.display.flip()
You want to add the colors at the intersections of the circles, hence use the BLEND_RGB_ADD flag.
I created a fourth surface since you wanted a white background.

How to center text inside a shape?

I want to display a number inside a circle.
The number must be centered (x,y).
How to do it?
import pygame, sys
pygame.init()
screen= pygame.display.set_mode((0, 0))
black= (0,0,0)
white= (255,255,255)
red= (255,0,0)
number= "8"
bigfont = pygame.font.SysFont("arial", 50)
text = bigfont.render(number, True, white)
def draw():
pygame.draw.circle(screen, red, (300,300), 200)
screen.blit(text, (300,300))
pygame.display.update()
Get the bounding rectangle of the text and set the center of the rectangle by the center of the text. Use the rectangle to blit the text:
text_rect = text.get_rect()
text_rect.center = (300, 300)
screen.blit(text, text_rect)
The same with one line of code:
screen.blit(text, text.get_rect(center = (300, 300)))
Use this code in a function:
def draw_circle(x, y, text):
pygame.draw.circle(screen, red, (x, y), 200)
screen.blit(text, text.get_rect(center = (x, y)))
See pygame.Surface.blit:
[...] The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit.
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
font = pygame.font.SysFont(None, 100)
clock = pygame.time.Clock()
text = font.render("Text", True, (255, 255, 0))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window_center = window.get_rect().center
window.fill(0)
pygame.draw.circle(window, (255, 0, 0), window_center, 100)
window.blit(text, text.get_rect(center = window_center))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
To centre PyGame text around point x_pos, y_pos:
Get the dimensions of the text object: width, height = text.get_rect()[2:4]
When you render (screen.blit()) the image, shift the coordinates back by half the width and half the height: screen.blit(text, (x_pos - int(width / 2), y_pos - int(height / 2)))

Can't get an image to have transparent background [duplicate]

This question already has answers here:
Pygame image transparency confusion
(1 answer)
How to convert the background color of image to match the color of Pygame window?
(1 answer)
Closed 1 year ago.
I am trying to import the image of a flappy bird, and even after .convert() or .convert_alpha() it's still not transparent? I flipped display right after converting, what am I missing?
import pygame
import os
from pipesforbird import Pipewall
pygame.init()
running = True
def player(x, y):
playerimg = pygame.image.load('birdo.png').convert()
screen.blit(playerimg, (x, y))
pygame.display.flip()
x = 50
y = 50
heigth = 60
width = 40
vel = 1
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
BLUE = (100, 100, 255)
BLACK = (0, 0, 0)
incomingpipes = pygame.sprite.Group()
greenPipewall = Pipewall(GREEN, 100, 300, 100)
greenPipewall.rect.x = 700
greenPipewall.rect.y = 0
secondPipewall2 = Pipewall(GREEN, 100, 400, -10)
secondPipewall2.rect.x = 1000
secondPipewall2.rect.y = 400
incomingpipes.add(greenPipewall)
incomingpipes.add(secondPipewall2)
while running:
screen = pygame.display.set_mode((800, 800))
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
y += vel
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
y -= (vel * 2)
if keys[pygame.K_ESCAPE]:
quit()
if y <= 100:
y = 100
if y >= 605:
y = 605
for Pipewall in incomingpipes:
Pipewall.moveLeft(vel)
if Pipewall.rect.x < -100:
Pipewall.rect.x = 800
screen.fill(BLUE)
incomingpipes.update()
incomingpipes.draw(screen)
pygame.draw.rect(screen, GREY, [0, 0, 800, 100], 0)
pygame.draw.rect(screen, GREY, [0, 650, 800, 200], 0)
player(x, y)
pygame.display.flip()
pygame.display.update()
quit()
this is the image in question (https://flyclipart.com/image-flappy-bird-png-767238)

Pygame buttons not creating working buttons

I am trying to make a hangman game in pygame, but I cannot get buttons to work after they have been created from an event (in my case after pressing enter), they appear on screen but do not work ( rollover or activate events), please help!
from pygame.locals import *
import pygame, sys, eztext
import time
pygame.init()
Black = ( 0, 0, 0)
Grey = (100, 100, 100)
DarkGrey = (70, 70, 70)
White = (255, 255, 255)
Blue = ( 0, 0, 255)
NavyBlue = ( 60, 60, 100)
Cyan = ( 0, 255, 255)
Purple = (255, 0, 255)
Red = (255, 0, 0)
DarkRed = (180, 0, 0)
Orange = (255, 128, 0)
Yellow = (255, 255, 0)
Green = ( 0, 255, 0)
DarkGreen = ( 0, 180, 0)
LightBlue = ( 90, 164, 213)
Magenta = (153, 0, 76)
screen = pygame.display.set_mode((1000,600),0,32)
screen.fill(Orange)
txtbx = eztext.Input(maxlength=45, color=(0,0,0), prompt='Enter username: ')
def text_objects(text, font):
textSurface = font.render(text, True, Black)
return textSurface, textSurface.get_rect()
smallText = pygame.font.Font("freesansbold.ttf",20)
def button(msg,x,y,w,h,ic,ac,action=None):
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(screen, ac,(x, y, w, h))
if click [0] == 1 and action!= None:
if action == "Quit":
pygame.quit()
if action == "Single player":
pygame.draw.rect(screen, Green,(10, 10, 500, 500))
else:
pygame.draw.rect(screen, ic,(x, y, w, h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(w/2)), (y + (h/2)))
screen.blit(textSurf, textRect)
while True:
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
string1 = txtbx.value
pygame.display.update()
time.sleep(0.02)
pygame.draw.rect(screen, Green,(10, 100, 500, 50))
clock = pygame.time.Clock()
clock.tick(30)
events = pygame.event.get()
txtbx.set_pos(10,110)
label = smallText.render("Enter you user name and then press enter!", 1, (0,0,0))
screen.blit(label, (10, 10))
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER or event.key == pygame.K_RETURN:
button("Single player",10, 400, 150, 50, Green, DarkGreen,"Single player")
if string1 in open('Users.txt').read():
username = string1
Welcomeold1 = smallText.render('Welcome back', 1, (0,0,0))
screen.blit(Welcomeold1, (10, 200))
Welcomeold2 = smallText.render(username, 1, (0,0,0))
screen.blit(Welcomeold2, (160, 200))
else:
username = string1
f = open('Users.txt','a')
string1 = txtbx.value
f.write(string1)
f.write('\n')
f.close()
Welcomenew1 = smallText.render('Welcome to my game', 1, (0,0,0))
screen.blit(Welcomenew1, (10, 200))
Welcomenew2 = smallText.render(username, 1, (0,0,0))
screen.blit(Welcomenew2, (230, 200))
if event.key == pygame.K_BACKSPACE:
screen.fill(Orange)
txtbx.update(events)
txtbx.draw(screen)
pygame.display.flip()
if __name__ == '__main__': main()
button function is inside event.key so it will work only when RETURN is pressed, released, and pressed again, and released again, etc.
You should create class with method draw and handle_event to use this method in mainloop in different places. You can create button in event.key but you have to check button pressed in different place.
-
Simple button. Full working example.
When you press button function do_it is called and background changed color.
#
# pygame (simple) template - by furas
#
# ---------------------------------------------------------------------
import pygame
import pygame.gfxdraw
import random
# === CONSTANS === (UPPER_CASE names)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
CYAN = ( 0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x, y, width, height, on_click=None, fg_color=RED, bg_color=WHITE, font_size=35):
self.text = text
font = pygame.font.SysFont(None, font_size)
# rectangle - without position, to put text in correct place
self.rect = pygame.Rect(0, 0, width, height)
# normal button - fill background
self.normal_image = pygame.surface.Surface( self.rect.size )
self.normal_image.fill(bg_color)
# normal button - add text
text_image = font.render(text, True, fg_color)
text_rect = text_image.get_rect(center=self.rect.center)
self.normal_image.blit(text_image, text_rect)
# hover button - fill background
self.hover_image = pygame.surface.Surface( self.rect.size )
self.hover_image.fill(fg_color)
# hover button - add text
text_image = font.render(text, True, bg_color)
text_rect = text_image.get_rect(center=self.rect.center)
self.hover_image.blit(text_image, text_rect)
# set position
self.rect.x = x
self.rect.y = y
# other
self.on_click = on_click
self.hover = False
def draw(self, surface):
# draw normal or hover image
if self.hover:
surface.blit(self.hover_image, self.rect)
else:
surface.blit(self.normal_image, self.rect)
def event_handler(self, event):
# is mouse over button ?
if event.type == pygame.MOUSEMOTION:
self.hover = self.rect.collidepoint(event.pos)
# is mouse clicked ? run function.
if event.type == pygame.MOUSEBUTTONDOWN:
if self.hover and self.on_click:
self.on_click()
# === FUNCTIONS === (lower_case names)
def do_it():
global background_color
if background_color == BLACK:
background_color = RED
elif background_color == RED:
background_color = GREEN
else:
background_color = BLACK
print("Button pressed")
# === MAIN ===
# --- init ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# --- objects ---
# create button
button = Button('CHANGE COLOR', 0, 0, 300, 50, on_click=do_it)
# add function later
#button_quit.on_click = do_it
# center button
button.rect.center = screen_rect.center
# default bacground color - changed in do_it()
background_color = BLACK
# --- mainloop ---
clock = pygame.time.Clock()
is_running = True
while is_running:
# --- events ---
for event in pygame.event.get():
# --- global events ---
if event.type == pygame.QUIT:
is_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
is_running = False
# --- objects events ---
button.event_handler(event)
# --- updates ---
# empty
# --- draws ---
# clear buffer
screen.fill(background_color)
# draw all objects - widgets (buttons, labels)
button.draw(screen)
clock.tick(25)
# send buffer to video card
pygame.display.update()
# --- the end ---
pygame.quit()

How do you create rect variables in python pygame

I am programming in Python with the pygame library. I want to know how to make a rectangle variable, something like:
import ...
rect1 = #RECT VARIABLE
rect2 = #RECT VARIABLE
Just do
pygame.Rect(left, top, width, height)
this will return you a Rect object in pygame
Perhaps something like this will work?
import pygame
# your whole code until you need a rectangle
rect1 = pygame.draw.rect( (x_coordinate, y_coordinate), (#a rgb color), (#size of rect in pixels) )
If you want a red rectangle with 100x150 size in 0x50 position, it will be:
rect1 = pygame.draw.rect( (0, 50), (255, 0, 0), (100, 150) )
To insert it into the screen you use:
pygame.screen_you_have_created.blit(rect1, 0, 50)
For rectangle draw pattern is : pygame.Rect(left, top, width, height)
You can modify this code according to your need.
import pygame, sys
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Title')
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
basicFont = pygame.font.SysFont(None, 48)
message = 'Hello '
text = basicFont.render(message, False, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
windowSurface.fill(WHITE)
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == K_ESCAPE:
pygame.quit()
sys.exit()

Categories

Resources