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

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)

Related

How to get mouse coordinates on a grid [duplicate]

This question already has answers here:
Is it possible to update a pygame drawing attribute when a event occurs?
(1 answer)
Python: How to make drawn elements snap to grid in pygame
(1 answer)
Closed 5 months ago.
I have a function to get a position on a grid (the size of the grid is flexible) based on the mouse position
def get_coords_from_mouse_pos(self, mx, my):
return mx // self.item_width, my // self.item_height
self.item_width and self.item_height are the width and height of one tile on the grid. mx and my are the mouse x and y positions. This probably exists somewhere else but I can't find it.
I probably just have the math wrong, but I would appreciate it if someone could help.
Here's a minimal example that shows your logic working, the left and top grid borders are considered as part of the cell below.
import pygame
# Configuration
width, height = 320, 240
cell_width, cell_height = 32, 32
pygame.init()
sys_font = pygame.font.SysFont(None, 60)
text = sys_font.render(" ", True, "turquoise")
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
# create transparent background grid
grid = pygame.Surface((width, height), flags=pygame.SRCALPHA)
for y in range(0, height, cell_height):
pygame.draw.aaline(grid, "green", (0, y), (width, y)) # horizontal lines
for x in range(0, width, cell_width):
pygame.draw.aaline(grid, "green", (x, 0), (x, height)) # vertical lines
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
mx, my = pygame.mouse.get_pos()
pygame.display.set_caption(f"Mouse: {mx}, {my}")
if mx > 0 and my > 0:
cellx = mx // cell_width
celly = my // cell_height
text = sys_font.render(f"Cell: {cellx}, {celly}", True, "turquoise")
# Graphics
screen.fill("grey25")
screen.blit(grid, (0, 0))
# Draw Text in the center
screen.blit(text, text.get_rect(center=screen.get_rect().center))
# Update Screen
pygame.display.update()
clock.tick(30)
pygame.quit()
This will look something like this:

how to center text in a rectangle in pygame [duplicate]

This question already has answers here:
How to Center Text in Pygame
(6 answers)
Closed 1 year ago.
im making a game in pygame and I can't figure out how I can center some text in a rectangle. I draw the rectangle by using pygame.draw_rect(win, color, (x, y, w, h)) and text with
text = font.render("text", 1, color).
i know I can use text_rect = text.get_Rect(), to get a rect object of the text. but I don't know how to use those to center the text. I was searching for a solution online and couldn't find it
You can get a rect from the surface generated by rendering your font. Then set the centre that rect to the centre of your rectangle. Then blit your font surface to the main surface.
Here's a small example that uses the mousewheel to enlarge and shrink the border rectangle to show that the font remains centred. Pressing a key randomises the text.
import random
import pygame
WIDTH, HEIGHT = 320, 240
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# use the first available font
font = pygame.font.SysFont(pygame.font.get_fonts()[0], 60)
pygame.display.set_caption("Centering Font Rect")
text = "Initial Text"
widget = font.render(text, True, pygame.Color("seagreen"))
border = pygame.Rect(10, 10, WIDTH - 40, HEIGHT - 40)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# change the text
text = random.choice(["Short", "Long Looooong", ".", "+++", "ABC"])
widget = font.render(text, True, pygame.Color("purple"))
elif event.type == pygame.MOUSEWHEEL:
# enlarge or shrink the border rect
border.inflate_ip(event.y, event.y)
screen.fill(pygame.Color("turquoise"))
# draw border rect
pygame.draw.rect(screen, pygame.Color("red"), border, width=1)
# get the current font rect
font_rect = widget.get_rect()
# move rect to be centered on border rect
font_rect.center = border.center
screen.blit(widget, font_rect)
# update display
pygame.display.update()
pygame.quit()
This shows:
Then after some resizing:

Text not outputting to pygame screen on button press [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How to detect when a rectangular object, image or sprite is clicked
(1 answer)
How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover
(1 answer)
Closed 2 years ago.
I want to code a very simple progam that outputs text to the pygame screen when i press a button, but for some reason it isn't outputting when i press the button. Any help? Thanks.
import pygame
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
X=800
Y=480
pygame.init()
pygame.font.init()
my_screen = pygame.display.set_mode((800, 480) ,
pygame.RESIZABLE)
my_font = pygame.font.Font('freesansbold.ttf' , 36)
text = my_font.render("Please wait, loading...",True,green)
textRect=text.get_rect()
textRect.center = (X // 2, Y //2)
pressed=False
boxThick=[0,10,10,10,10,10]
still_looping =True
while still_looping:
for event in pygame.event.get():
if event.type==pygame.QUIT:
still_looping=False
pygame.draw.rect(my_screen,(0,255,0),(0,0,200,200),boxThick[0])
pygame.draw.rect(my_screen,(50,50,50),(200,200,100,50),0)
a,b,c = pygame.mouse.get_pressed()
if a:
pressed = True
else:
if pressed == True:
x,y = pygame.mouse.get_pos()
if x> 200 and x<300 and y>200 and y<200:
my_screen.blit(text,textRect)
pressed = False
pygame.display.update()
The text is not displayed because the conditions y>200 and y<200 is always evaluated with False. Since the height of the rectangular area is 50, the condition must be y>200 and y<250:
if x> 200 and x<300 and y>200 and y<200:
if x> 200 and x<300 and y>200 and y<250:
# [...]
Since comparison operators can be chained in Python, the code can be simplified:
if 200 < x < 300 and 200 < y < 250:
# [...]
However, if you want to test that the mouse pointer is in a rectangular area, I recommend using a pygame.Rect object and collidepoint():
rect = pygame.Rect(200, 200, 100, 50)
x, y = pygame.mouse.get_pos()
if rect .collidepoint(x, y):
# [...]

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))

Displaying text with pygame [duplicate]

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)

Categories