pygame.font not working and not showing any errors also - python

Everything is working fine except that font thing, i don't know why it's happening and it's not even showing any error. And not displaying the Text on screen.
# import library here
import pygame
import time
import sys
# display init
display_width = 800
display_height = 600
# game initialization done
pygame.init()
# game display changed
gameDisplay = pygame.display.set_mode((display_width, display_height))
# init font object with font size 25
font = pygame.font.SysFont(None, 25)
def message_to_display(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [10, 10])
message_to_display("You Lose", red)
time.sleep(3)
pygame.quit()
# you can signoff now, everything looks good!
quit()

The reason you see nothing is because you haven't updated or 'flipped' the display. After you've created the text Surface and blit it to the gameDisplay Surface you have to update/'flip' the display so it becomes visible to the user.
So, between message_to_display("You Lose", red) and time.sleep(3) you put pygame.display.update()or pygame.display.flip() (it doesn't matter which). Like this:
# import library here
import pygame
import time
import sys
# display init
display_width = 800
display_height = 600
# game initialization done
pygame.init()
# game display changed
gameDisplay = pygame.display.set_mode((display_width, display_height))
# init font object with font size 25
font = pygame.font.SysFont(None, 25)
def message_to_display(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [10, 10])
message_to_display("You Lose", red)
pygame.display.update() # VERY IMPORTANT! THIS IS WHAT YOU MISSED!
time.sleep(3)
pygame.quit()
# you can signoff now, everything looks good!
quit()
Also, as J.J. Hakala pointed out, you have to define red in message_to_display("You Lose", red) as well.

Related

pygame not displaying my image

i started learning pygame and i followed some tutorials to make simple hello world project and it works but when i do it my self trying to display my image on the window nothing happen!
this is my code
__author__ = 'mohammed'
import sys
import pygame
import color
# -----------setup------------------------
pygame.init() # start pygame
screensize = (800, 600) # variable that we will use to declare screen size
screen = pygame.display.set_mode(screensize) # set the screen size
pad = pygame.image.load('2.png')
x = 100
y = 100
# -----------setup------------------------
# -------------------main loop------------
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(pad, (x, y))
screen.fill(red)
pygame.display.update()
i am importing my file that contain colors and their rgb :
red = (255, 0, 0)
It looks like you're filling the screen after the image is drawn, covering the image. Try switching the order of the rows:
screen.blit(pad, (x, y))
and
screen.fill(red)

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.

Why does this pygame program freeze?

Below is a program using pygame which updates the histogram as values change.
However after a few seconds of running, the program freezes. Can someone point out the error?
import random
import pygame
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
FRAME_RATE = 50
BACKGROUND_COLOR = pygame.Color("white")
BAR_COLOR = pygame.Color("Black")
BUCKET_CNT = 20
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
screen.fill(BACKGROUND_COLOR)
buckets = BUCKET_CNT*[0]
bar_w = SCREEN_WIDTH / BUCKET_CNT
clock = pygame.time.Clock()
background = pygame.Surface(screen.get_size())
background.fill(BACKGROUND_COLOR)
while True:
clock.tick(FRAME_RATE)
random.seed()
idx = random.randrange(BUCKET_CNT)
buckets[idx] += 1
# Create rectangles representing bars in the histogram.
bars = [pygame.Rect(i*bar_w,
SCREEN_HEIGHT - buckets[i],
bar_w, buckets[i]) for i in range(BUCKET_CNT)]
# Draw bars on the background
[pygame.draw.rect(background, BAR_COLOR, b, 5) for b in bars]
# Blit the background
screen.blit(background, (0, 0))
# Show "stuff" on the screen
pygame.display.flip()
EDIT
These are very good suggestions. I've changed my code using to follow them, however the code still freezes. Here is how the code looks now:
import random
import pygame
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
FRAME_RATE = 50
BACKGROUND_COLOR = pygame.Color("white")
BAR_COLOR = pygame.Color("Black")
BUCKET_CNT = 20
GROWTH_RATE = 10
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
screen.fill(BACKGROUND_COLOR)
buckets = BUCKET_CNT*[0]
bar_w = SCREEN_WIDTH / BUCKET_CNT
clock = pygame.time.Clock()
background = pygame.Surface(screen.get_size())
background.fill(BACKGROUND_COLOR)
# Create rectangles representing bars in the histogram.
bars = [pygame.Rect(i*bar_w,
SCREEN_HEIGHT - buckets[i],
bar_w, buckets[i]) for i in range(BUCKET_CNT)]
random.seed()
while True:
clock.tick(FRAME_RATE)
idx = random.randrange(BUCKET_CNT)
buckets[idx] += 1
bars[idx].inflate_ip(0, GROWTH_RATE)
# Draw bars on the background
pygame.draw.rect(background, BAR_COLOR, bars[idx])
# Blit the background
screen.blit(background, (0, 0))
# Show "stuff" on the screen
pygame.display.flip()
I want to apologize for taking everybody's time. As it turns out there is no issue with the code. My work machine was simply overloaded with various processes. It is running a multi-threaded test and a virtual machine (which is currently compiling a very large code base). That all explains why my program was freezing. Thank you DJMcMayhem for trying out the code. A special shout out to Alex Van Leiw. Thanks to you I learned a few new things about pygame today.

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

Categories