Displaying text with pygame [duplicate] - python

This question already has answers here:
How to display text in pygame? [duplicate]
(4 answers)
Closed 9 years ago.
import pygame, sys
from pygame.locals import *
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('P.Earth')
while 1: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.update()
import time
direction = ''
print('Welcome to Earth')
pygame.draw.circ(screen, RED, [55,500,10,5], 0)
time.sleep(1)
print('Earth was a very prosperous planet. Filled with life and culture.')
time.sleep(2)
This is only a part of it. It doesn't display on the pygame screen. (in case you're wondering i do use pygame.quit() at the end) I just want it to work. If you could make your answers simpler, that'd be great because i'm still a beginner. How would i display the text? any help will do. thanks.

You're looking to use the pygame font module.
Here's an example of rendering then positioning the font on your screen. ()
import pygame.font
font = pygame.font.Font(None, 36) # None can be a font file instead
text = font.render("Welcome to Earth", 1, (0, 0, 0))
# Determine the location that should be allocated for the text
text_box = text.get_rect(centerx=DISPLAYSURF.get_width()/2)
# Draw the text onto the background
background.blit(text, text_box)

Related

Transparency problem displaying text with Pygame

enter image description hereI would like to display transparent text on a surface that is sized based on the length of the text.
The problem is that the text has a black background even though "None" is specified as the background in the "render" command.
I tried to apply the solutions given for questions similar to mine but they didn't work.
I attach the code and thank you for any suggestions.
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill ((0,0,255))
# red square
surf1 = pygame.Surface((200, 200))
surf1.fill((255, 0, 0))
rect1 = surf1.get_rect()
rect1.topleft = (50, 50)
screen.blit(surf1, rect1)
# Play button
fnt = pygame.font.SysFont("Times New Roman", 27, bold=True)
btn_play = fnt.render("Play", True, (51, 26, 0), None)
btn_play_size = btn_play.get_size()
btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface.blit(btn_play, (0, 0))
rect_btn_play = pygame.Rect(380, 50, btn_play_size[0], btn_play_size[1])
screen.blit(btn_play_surface, (380, 50))
pygame.display.flip()
def events():
done = False
while not done:
for ev in pygame.event.get():
if ev.type == QUIT:
return "quit"
elif ev.type == MOUSEBUTTONDOWN:
click = ev.pos
if rect1.collidepoint(click):
return "Red squre"
elif rect_btn_play.collidepoint(click):
return "Play"
else:
print ("You clicked outside of the surfaces")
while True:
event = events()
print (event)
if event == "quit":
break
pygame.quit()
The problem is the surface you are placing the text on. If you want to keep the transparency in the formation of the text, you need to create a pygame.Surface object with an per pixel alpha format. Use the pygame.SRCALPHA flag:
btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface = pygame.Surface(btn_play_size, pygame.SRCALPHA)
Alternatively you can set the color key for the transparent color with set_colorkey:
btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface.set_colorkey((0, 0, 0))

How do you center text being displayed with pygame? [duplicate]

This question already has answers here:
How to Center Text in Pygame
(6 answers)
Pygame: Centering text system font text
(1 answer)
Closed 2 years ago.
I have this code and it's not displaying the text assigned to the variable "title" in the middle of the width of the screen.
Is there any way to center it other than guessing the positions based on how long the text is?
import pygame
pygame.init()
pygame.font.init()
WIDTH = 1920
HEIGHT = 1080
CYAN = (0, 255, 255)
RED = (255, 0, 0)
window = pygame.display.set_mode((WIDTH, HEIGHT))
def startWindow():
titleFont = pygame.font.SysFont("Comic Sans MS", 35)
window.fill(RED)
title = titleFont.render("Ball Game", False, CYAN)
window.blit(title, (WIDTH//2, 35))
pygame.display.update()
startWindow()
You should first get the text rectangle after rendering it, then center the rectangle relative to the screen width. Afterwhich you can pass it into blit.
centerTitle = title.get_rect(center=(WIDTH/2,35))
window.blit(title, centerTitle)

Very simple PyGame very slow [duplicate]

This question already has answers here:
Lag when win.blit() background pygame
(2 answers)
Closed 2 years ago.
I want to make a (a bit bigger) game in PyGame, but even with this simple code I just get arround 10 fps instead of 60? Here's the code:
import pygame
res = 1280,720
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")
background = pygame.transform.smoothscale(pygame.image.load("Background.png"), res)
a = 0
while True:
pygame.time.Clock().tick(60)
display.fill((0,0,0))
a += 10
display.blit(background, (0,0)) #Without this line: arround 20 fps
pygame.draw.rect(display,(255,0,0), (a,8,339,205))
pygame.display.update()
pygame.quit()
What am I doing wrong?
Thank you!
Try the following optimizations:
Use the convert() method on your image pygame.image.load("Background.png").convert()). This makes the animation about 5 times faster.
Instead of re-blitting entire background every frame, only update the changed parts of the screen.
You don't need to clear the screen before drawing the background.
Use the same Clock instance every frame.
Here's the code:
import pygame
pygame.init()
res = (1280, 720)
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")
background = pygame.transform.smoothscale(pygame.image.load(r"E:\Slike\Bing\63.jpg").convert(), res)
a = 0
clock = pygame.time.Clock()
display.blit(background, (0, 0))
pygame.display.update()
while True:
clock.tick(60)
rect = (a,8,339,205)
display.blit(background, rect, rect) # draw the needed part of the background
pygame.display.update(rect) # update the changed area
a += 10
rect = (a,8,339,205)
pygame.draw.rect(display, (255,0,0), rect)
pygame.display.update(rect) # update the changed area

How to centre an image in pygame? [duplicate]

This question already has an answer here:
How to center an image in the middle of the window in pygame?
(1 answer)
Closed 6 months ago.
I am using python 2.7, I would like to know if there is a way to centre an image in pygame. I have set the screen to fullscreen, is this possible? If it helps i will attach the code, thanks.
import pygame
import os
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
pygame.init()
screen = pygame.display.set_mode((0, 0))
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill((0, 0, 0))
screen.blit(get_image('sw.png'), (0, 0)
pygame.display.flip()
clock.tick(60)
Yeah, it's possible.
You have to create a rect object of the image:
image = "insert image"
rect = image.get_rect ()
And then:
rect.center = ("coordinates of center")
This StackOverflow question might be able to help you.
Pygame Image position
Basically though, you'd get the image rectangle. From there there are a lot of useful functions you can call to position it.

How to display text in pygame? [duplicate]

This question already has answers here:
pygame - How to display text with font & color?
(7 answers)
Closed 2 years ago.
I can't figure out to display text in pygame.
I know I can't use print like in regular Python IDLE but I don't know how.
import pygame, sys
from pygame.locals import *
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('P.Earth')
while 1: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.update()
import time
direction = ''
print('Welcome to Earth')
pygame.draw.rect(screen, RED, [55,500,10,5], 0)
time.sleep(1)
This is only the beginning part of the whole program.
If there is a format that will allow me to show the text I type in the pygame window that'd be great. So instead of using print I would use something else. But I don't know what that something else is.
When I run my program in pygame it doesn't show anything.
I want the program to run in the pygame window instead of it just running in idle.
You can create a surface with text on it. For this take a look at this short example:
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
my_font = pygame.font.SysFont('Comic Sans MS', 30)
This creates a new object on which you can call the render method.
text_surface = my_font.render('Some Text', False, (0, 0, 0))
This creates a new surface with text already drawn onto it.
At the end you can just blit the text surface onto your main screen.
screen.blit(text_surface, (0,0))
Bear in mind, that every time the text changes, you have to recreate the surface again, to see the new text.
There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.
Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.
You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.
import pygame
import pygame.freetype # Import the freetype module.
pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255,255,255))
# You can use `render` and then blit the text surface ...
text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
screen.blit(text_surface, (40, 250))
# or just `render_to` the target surface.
GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))
pygame.display.flip()
pygame.quit()
When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:
import pygame
def text_to_screen(screen, text, x, y, size = 50,
color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
try:
text = str(text)
font = pygame.font.Font(font_type, size)
text = font.render(text, True, color)
screen.blit(text, (x, y))
except Exception, e:
print 'Font Error, saw it coming'
raise e
Then when that has been imported when I want to display text taht updates E.G score I do:
Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)
If it is just normal text that isn't being updated:
Funk.text_to_screen(screen, 'Text', xpos, ypos)
You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))

Categories