Can't find a way to make multiple lines in pygame - python

I'm aware of the fact that pygame's screen.blit is not meant to support multiple lines, however I can't figure out a work around. All of the other threads that ask this question just don't work with my code. How do I make this work?
I've tried to split response into two by using splitline() on DisplayRoom.prompt and then having the game just load two lines separately, but DisplayRoom.prompt.splitline() does not turn `DisplayRoom.prompt from a tuple to a list and only returns the value for it.
screen.fill(background_colour)
txt_surface = userfont.render(text, True, color)
screen.blit(txt_surface, (100, 800))
response = promptfont.render(DisplayRoom.prompt, True, color)
screen.blit(response, (80, 300))
pygame.display.flip()
clock.tick_busy_loop(60) # limit FPS
When I defined DisplayRoom.prompt, I expected \n to linebreak it but it doesn't work which is why I'm here.

It is not Surface.blit which doesn't support multiple lines. blit simply draw a Surface on another Surface, it doesn't care what the Surface contains.
It's pygame.Font.render which doesn't support multilines. The docs clearly say:
The text can only be a single line: newline characters are not rendered.
So I don't know what DisplayRoom.prompt is in your code, but if is not a string, is bound to fail: render raises a TypeError: text must be a unicode or bytes.
And if is a string with newlines, newlines are just not rendered.
You have to split the text and render each line separately.
In the following example I create a simple function blitlines which illustrates how you could do.
import sys
import pygame
def blitlines(surf, text, renderer, color, x, y):
h = renderer.get_height()
lines = text.split('\n')
for i, ll in enumerate(lines):
txt_surface = renderer.render(ll, True, color)
surf.blit(txt_surface, (x, y+(i*h)))
background_colour = (0, 0, 0)
textcolor = (255, 255, 255)
multitext = "Hello World!\nGoodbye World!\nI'm back World!"
pygame.init()
screen = pygame.display.set_mode((500, 500))
userfont = pygame.font.Font(None, 40)
screen.fill(background_colour)
blitlines(screen, multitext, userfont, textcolor, 100, 100)
pygame.display.flip()
#main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
This is the result on the screen.

Related

Two Surfaces not bliting pygame

I'm trying to render some font onto my Pygame screen but it never shows up. I think I have everything set-up right and my programs not throwing any errors so I'm not sure what's wrong. This is the code I'm using to try and create the text:
pygame.init()
pygame.display.set_caption("MyGame")
font = SysFont("Times", 24) #Create a new font using times if it exists, else use system font.
white = (255, 255, 255)
while True: #Game loop
label = font.render("Score: " + str(score), 1, white)
self.surface.blit(label, (100, 100))
# Do other game things....
self.board.draw()
pygame.display.update()
self.clock.tick(60)
and in my init function:
def __init__(self):
self.surface = pygame.display.set_mode((400, 500)) #Set dimensions of game window. Creates a Surface
self.clock = pygame.time.Clock()
self.board = Board(self.surface) # Board is an object in my game
What am I doing wrong? I've looked all over the Pygame documentation and SO but I can't see anything wrong in my code. I've also tried setting the font explicitly with
font = pygame.font.Font("/System/Library/Fonts/Helvetica.dfont", 24)
but nothing seems to work.
As furas suggested, the problem was caused by me filling in the surface after drawing.

Making text appear one character at a time [PyGame]

I am trying to make the dialog appear one character at a time (Like in Pokemon games and other similar).
I have searched over the internet but have not managed to find anything helpful.
I am aware of another question asked like this, but it didn't solve what I am trying to do. I know this can be done because I have seen games made with python where this has been done.
import pygame, sys
from pygame.locals import *
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
def display_text_animation(string):
text = ''
for i in range(len(string)):
DISPLAYSURF.fill(WHITE)
text += string[i]
text_surface = font.render(text, True, BLACK)
text_rect = text_surface.get_rect()
text_rect.center = (WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
DISPLAYSURF.blit(text_surface, text_rect)
pygame.display.update()
pygame.time.wait(100)
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
display_text_animation('Hello World!')
main()
NOTE: I haven't used pygame before so this may not work.
The below works very well. And stops any overloading of the event queue (so multiple lines or lots of text don't stall the animation). This is necessary if embedded in a simple application that doesn't handle the event queue in some other way.
line_space = 16
basicfont = pygame.font.SysFont('MorePerfectDOSVGA', 16)
def text_ani(str, tuple):
x, y = tuple
y = y*line_space ##shift text down by one line
char = '' ##new string that will take text one char at a time. Not the best variable name I know.
letter = 0
count = 0
for i in range(len(str)):
pygame.event.clear() ## this is very important if your event queue is not handled properly elsewhere. Alternativly pygame.event.pump() would work.
time.sleep(0.05) ##change this for faster or slower text animation
char = char + str[letter]
text = basicfont.render(char, False, (2, 241, 16), (0, 0, 0)) #First tuple is text color, second tuple is background color
textrect = text.get_rect(topleft=(x, y)) ## x, y's provided in function call. y coordinate amended by line height where needed
screen.blit(text, textrect)
pygame.display.update(textrect) ## update only the text just added without removing previous lines.
count += 1
letter += 1
print char ## for debugging in console, comment out or delete.
text_ani('this is line number 1 ', (0, 1)) # text string and x, y coordinate tuple.
text_ani('this is line number 2', (0, 2))
text_ani('this is line number 3', (0, 3))
text_ani('', (0, 3)) # this is a blank line
This is a bit more simplistic, it creates a function which you can use whenever you want. In this example I called my function 'slow' and made it so that you need to input a string when calling it. Whatever is inputted will display character by character. The speed depends on the value near 'sleep'. Hope this helped.
from time import * #imports all the time functions
def slow(text): #function which displays characters one at a time
for letters in text: #the variable goes through each character at a time
print(letters, end = "") #current character is printed
sleep(0.02) #insert the time between each character shown
#the for loop will move onto the next character
slow("insert text here") #instead of print, use the name of the function
If you run this as it is, it should output "insert text here" one character at a time.

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

How to add text into a pygame rectangle

I have come as far as drawing a rectangle in pygame however I need to be able to get text like "Hello" into that rectangle. How can I do this? (If you can explain it as well that would be much appreciated. Thank-you)
Here is my code:
import pygame
import sys
from pygame.locals import *
white = (255,255,255)
black = (0,0,0)
class Pane(object):
def __init__(self):
pygame.init()
pygame.display.set_caption('Box Test')
self.screen = pygame.display.set_mode((600,400), 0, 32)
self.screen.fill((white))
pygame.display.update()
def addRect(self):
self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
pygame.display.update()
def addText(self):
#This is where I want to get the text from
if __name__ == '__main__':
Pan3 = Pane()
Pan3.addRect()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit();
Thank you for your time.
You first have to create a Font (or SysFont) object. Calling the render method on this object will return a Surface with the given text, which you can blit on the screen or any other Surface.
import pygame
import sys
from pygame.locals import *
white = (255,255,255)
black = (0,0,0)
class Pane(object):
def __init__(self):
pygame.init()
self.font = pygame.font.SysFont('Arial', 25)
pygame.display.set_caption('Box Test')
self.screen = pygame.display.set_mode((600,400), 0, 32)
self.screen.fill((white))
pygame.display.update()
def addRect(self):
self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
pygame.display.update()
def addText(self):
self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100))
pygame.display.update()
if __name__ == '__main__':
Pan3 = Pane()
Pan3.addRect()
Pan3.addText()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit();
Note that your code seems a little bit strange, since usually you do all the drawing in the main loop, not beforehand. Also, when you make heavy use of text in your program, consider caching the result of Font.render, since it is a very slow operation.
Hi!
To be honestly there is pretty good ways to write text in any place of current rect.
And now i'll show how to do it pretty easy.
First of all we need to create object of rect instance:
rect_obj = pygame.draw.rect(
screen,
color,
<your cords and margin goes here>
)
Now rect_obj is object of pygame.rect instance. So, we are free to manipulate with this methods. But, beforehand lets create our rendered text object like this:
text_surface_object = pygame.font.SysFont(<your font here>, <font size here>).render(
<text>, True, <color>
)
Afterall we are free to manipulate with all methods, as i mensioned before:
text_rect = text_surface_object.get_rect(center=rect_obj.center)
What is this code about?
We've just got center cords of out current rect, so easy!
Now, you need to blit ur screen like this:
self.game_screen.blit(text_surface_object, text_rect)
Happy coding! :)

Update display all at one time PyGame

Using PyGame, I get flickering things. Boxes, circles, text, it all flickers. I can reduce this by increasing the wait between my loop, but I though maybe I could eliminate it by drawing everything to screen at once, instead of doing everything individually. Here's a simple example of what happens to me:
import pygame, time
pygame.init()
screen = pygame.display.set_mode((400, 300))
loop = "yes"
while loop=="yes":
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
pygame.display.update()
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update()
time.sleep(0.1)
The "Begin" button flickers for me. It could just be my slower computer, but is there a way to reduce or eliminate the flickers? In more complex things I'm working on, it gets really bad. Thanks!
I think part of the problem is you're calling 'pygame.display.update()' more then once. Try calling it only once during the mainloop.
Some other optimizations:
You could take the font creation code out of the main loop to speed things up
Do loop = True rather then loop = "yes"
To have a more consistent fps, you could use Pygame's clock class
So...
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
loop = True
# No need to re-make these again each loop.
font1 = pygame.font.SysFont("calibri",40)
font2 = pygame.font.SysFont("calibri",20)
fps = 30
clock = pygame.time.Clock()
while loop:
screen.fill((0, 0, 0), (0, 0, 400, 300))
text = font1.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
text = font2.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update() # Call this only once per loop
clock.tick(fps) # forces the program to run at 30 fps.
You're updating your screen 2 times in a loop, one for drawing first text(TextA) and one for second text(Begin).
After your first update, only first text appears, so you can't see begin text between first update and second update. This causes flickering.
Update your screen after drawing everything. In your case, remove first pygame.display.update().
You're redrawing the content of your entire screen every 0.1 seconds. It's much more common and faster to keep track of the changes you actual make and only update the rects that actually contain changed content. So draw everything outside of your loop and have your events modify the screen and keep track of the rectangles that actually are changed.
So something like this:
import pygame, time
pygame.init()
screen = pygame.display.set_mode((400, 300))
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
loop = "yes"
counter = 0
dirty_rects = []
while loop=="yes":
pygame.display.update()
time.sleep(0.1)
# Handle events, checks for changes, etc. Call appropriate functions like:
counter += 1
if counter == 50:
font = pygame.font.SysFont("calibri",20)
text = font.render("We hit 50!", True,(255,255,255))
screen.blit(text,(50,100))
dirty_rects.append(Rect((50,100),text.get_size()))
Pygame has a Buffer system to avoid flickering, so you should draw them as you are doing, but update only once at the end:
...
while loop=="yes":
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update() # only one update
time.sleep(0.1)
And Pygame has a Clock Class that is better than time.sleep(0.1) if you wan't to keep a framerate.

Categories