I'm having trouble with the framerate in my game. I've set it to 60 but it only goes to ~25fps. This was not an issue before displaying the background (was fine with only win.fill(WHITE)). Here is enough of the code to reproduce:
import os, pygame
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50, 50)
pygame.init()
bg = pygame.image.load('images/bg.jpg')
FPS = pygame.time.Clock()
fps = 60
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
winW = 1227
winH = 700
win = pygame.display.set_mode((winW, winH))
win.fill(WHITE)
pygame.display.set_icon(win)
def redraw_window():
#win.fill(WHITE)
win.blit(bg, (0, 0))
win.blit(text_to_screen('FPS: {}'.format(FPS.get_fps()), BLUE), (25, 50))
pygame.display.update()
def text_to_screen(txt, col):
font = pygame.font.SysFont('Comic Sans MS', 25, True)
text = font.render(str(txt), True, col)
return text
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
redraw_window()
FPS.tick(fps)
pygame.quit()
Ensure that the background Surface has the same format as the display Surface. Use convert() to create a Surface that has the same pixel format. That should improve the performance, when the background is blit to the display, because the formats are compatible and blit do not have to do an implicit transformation.
bg = pygame.image.load('images/bg.jpg').convert()
Furthermore, it is sufficient to create the font once, rather than every time when a text is drawn. Move font = pygame.font.SysFont('Comic Sans MS', 25, True) to the begin of the application (somewhere after pygame.init() and before the main application loop)
Instead use screen.blit(pygame.image.load(picture.png))
Just image = pygame.image.load(picture.png) then screen.blit(image)
( if you keep loading your pictures continuously it will get lag )
Related
I've been trying to put text over a sprite (a dialogue box I imported) but no text comes up. The current code is me trying to blit the text onto the screen but it isn't working. The code works on a separate document, just not on this one. I currently have it creating the colour, then a box for the text to display in. After that, the box is made to fit its surroundings, a font is initialised through SysFont. Then my text is blit to the screen with a display.update to keep it constantly up the top of the layers. Even after hashing the code that creates the sprites and blits them, the text doesn't show up and instead the mouse coordinates and keyboard and mouse buttons are shown underneath the screen in a textbox. Anything helps as I'm new to coding.
import pygame
import os
import random
import sys
pygame.init()
pygame.font.init()
# Create Screen
FrameHeight = 3000
FrameWidth = 10000
screen = pygame.display.set_mode((FrameWidth, FrameHeight))
#Create Sprites
flag = True
background = pygame.image.load("fantasy-village-bg.jpg")
icon1 = pygame.image.load("Elder.png")
Dialogue = pygame.image.load("Dialogue-box.png")
def village():
#Repeating loop for beginning shot of the game
while flag == True:
#Background loops
screen.fill((23, 234, 80))
screen.blit(background, (0, 0))
#Village elder loops
screen.blit(icon1, (0, 0))
#Dialogue box loops
screen.blit(Dialogue, (-100, 400))
pygame.display.flip()
village()
# PYGAME FRAME WINDOW and documentation for keylogging and mouse tracking
pygame.mouse.set_visible(0)
pygame.display.set_caption("Riftka: Adventure Awaits")
#Dealing with the event of a crash"""
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
print(event)
pygame.display.update()
#First set of dialogue
black = (0,0,0)
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
def show_text( msg, color, x=WINDOW_WIDTH//2, y=WINDOW_WIDTH//2 ):
global WINDOW
text = font.render( msg, True, color)
WINDOW.blit(text, ( x, y ) )
pygame.init()
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")
# Create the font (only needs to be done once)
font = pygame.font.SysFont(None, 25)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
show_text("We have been waiting for you traveller", blue)
pygame.display.update()
Images are layered in the order they're blit to the screen.
I've separated out your display text loop and added in some draw functions to show the layering
import pygame
pygame.init()
black = (0,0,0)
blue = pygame.Color("dodgerblue")
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
def show_text( window, font, msg, color,):
text = font.render( msg, True, color)
# center the text on the window
text_rect = text.get_rect(center=window.get_rect().center)
window.blit(text, text_rect)
pygame.init()
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")
# Create the font (only needs to be done once)
font = pygame.font.SysFont(None, 25)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
WINDOW.fill(black)
pygame.draw.rect(WINDOW, pygame.Color("purple"), [250, 200, 200, 100])
show_text(WINDOW, font, "We have been waiting for you traveller", blue)
pygame.draw.rect(WINDOW, (pygame.Color("red")), [320, 220, 50, 60])
pygame.display.update()
clock.tick(30) # limit FPS
This should look something like this:
This question already has answers here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
As i mention, i'm super new in pygame and need help with this. I'm just testing the pygame commands, and want to show up a white screen with a message whenever i initialize the game and press any key, but apparently, it's not working. Here's my code:
# pygame template
import pygame
# import random
WIDTH = 400
HEIGHT = 500
FPS = 60
TITLE = 'My Game'
FONT_NAME = 'SNAKE/DinoTopia.ttf'
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
CLOCK = pygame.time.Clock()
# classes
class Main:
def __init__(self):
self.running = False
self.game_font = pygame.font.match_font(FONT_NAME)
def show_screen(self):
if self.running is True:
SCREEN.fill(WHITE)
self.draw_text('HELLO', 50, WIDTH/2, HEIGHT/2, BLUE)
pygame.display.flip()
self.wait_for_key()
def wait_for_key(self):
for key in pygame.event.get():
if key.type == pygame.KEYUP:
self.running = True
self.show_screen()
def draw_text(self, text, size, x, y, color):
font = pygame.font.Font(self.game_font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
SCREEN.blit(text_surface, text_rect)
g = Main()
# game loop
running = True
while running:
# keep loop running at the right speed
CLOCK.tick(FPS)
# process input
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# update
# draw/ render
SCREEN.fill(BLACK)
g.wait_for_key()
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
i know something may be wrong with the wait_for_key function but i can't see what it is, so a little help would be nice! thanks in advance!
show screen function is only called when a key is up. A single frame. You have to call it every frame. Also don't call pygame.event.get and pygame.display.flip more than once.
# pygame template
import pygame
# import random
WIDTH = 400
HEIGHT = 500
FPS = 60
TITLE = 'My Game'
FONT_NAME = 'SNAKE/DinoTopia.ttf'
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
CLOCK = pygame.time.Clock()
# classes
class Main:
def __init__(self):
self.running = False
self.game_font = pygame.font.match_font(FONT_NAME)
def show_screen(self):
if self.running:
SCREEN.fill(WHITE)
self.draw_text('HELLO', 50, WIDTH/2, HEIGHT/2, BLUE)
def wait_for_key(self, events):
for event in events:
if event.type == pygame.KEYUP:
self.running = True
def draw_text(self, text, size, x, y, color):
font = pygame.font.Font(self.game_font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
SCREEN.blit(text_surface, text_rect)
g = Main()
# game loop
running = True
while running:
# keep loop running at the right speed
CLOCK.tick(FPS)
# process input
events = pygame.event.get()
for event in events:
# check for closing window
if event.type == pygame.QUIT:
running = False
# update
# draw/ render
SCREEN.fill(BLACK)
g.wait_for_key(events)
g.show_screen()
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
I want to rotate the screen of my pygame window by 90 degrees and am unable to find any function to do so. I tried p.transform.rotate() but i guess that is used for Images only. Any help would be deeply appreciated
Of course you can use pygame.transform.rotate(). pygame.display.set_mode() just generates a pygame.Surface which is associated to the display.
However, pygame.transform.rotate() returns a new but rotated pygame.Surface object. Therefore you must blit the surface back on the dispaly:
window.blit(pygame.transform.rotate(window, 90), (0, 0))
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
font = pygame.font.SysFont(None, 100)
clock = pygame.time.Clock()
text = font.render("Display", True, (255, 255, 0))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(text, text.get_rect(center = window.get_rect().center))
window.blit(pygame.transform.rotate(window, 90), (0, 0))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Why is nothing drawn in PyGame at all?
(2 answers)
Closed 1 year ago.
I tried to make a clone of a game but the rectangle (which is the basic shape that I will need)does not appear. What did I do wrong or its just pygame going crazy?
code:
# importing modules
import pygame
import sys
import random
# starting pygame
pygame.init()
# making a screen
(width, height) = (500, 500)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Mincraft')
running = True
# fps counter
clock = pygame.time.Clock()
print(clock)
# geting the x button to work
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
pygame.display.quit()
pygame.quit()
exit()
# colors
white = (255, 255, 255)
blue = (0, 0, 255)
red = (255, 0, 0)
green = (4, 255, 0)
# cube
if running == True:
pygame.draw.rect(screen, blue, (395, 0, 10, 10)),
pygame.draw.rect(screen, blue, (395, 10, 10, 10)),
pygame.draw.rect(screen, blue, (395, 20, 10, 10)),
clock.tick(60)
and also how am I going to make it empty and 3d. I know I am asking for a lot but I believe someone can explain
You have to draw the scene in the application loop:
# importing modules
import pygame
import sys
import random
# colors
white = (255, 255, 255)
blue = (0, 0, 255)
red = (255, 0, 0)
green = (4, 255, 0)
# starting pygame
pygame.init()
# making a screen
(width, height) = (500, 500)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Mincraft')
running = True
# fps counter
clock = pygame.time.Clock()
print(clock)
# geting the x button to work
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.draw.rect(screen, blue, (395, 0, 10, 10))
pygame.draw.rect(screen, blue, (395, 10, 10, 10))
pygame.draw.rect(screen, blue, (395, 20, 10, 10))
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
exit()
The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
limit frames per second to limit CPU usage with pygame.time.Clock.tick
I am creating a game using pygame 1.9.6. But, as you can see by running this simple example, some black borders appear around the window, even with the FULLSCREEN flag.
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((900, 500), FULLSCREEN)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill((255, 255, 255))
pygame.display.flip()
I tried to add the flag NOFRAME in the screen initialisation, but it didn't work.
I wonder if it is possible to remove the border, for example by increasing the screen size to just fit in the current screen. But I also want to keep the 900x500 resolution.
Can pygame resize the entire screen? Do I have to blit() everything on a Surface, then rescale it and draw it on the actual screen?
Thanks #Glenn Mackintosh!
The best way to remove the black border is actually to add the SCALED flag in the screen declaration like this:
screen = pygame.display.set_mode((900, 500), FULLSCREEN|SCALED)
But to use it, the pygame version 2.0.0 or more is required.
The only way to remove the black bars is to set the pygame.display.set_mode((width, height)) to the users resolution. Use pygame.display.Info() to get the users' display resolution. Furthermore, you can have a preferred resolution such as 900 x 500 to get a "differential number" to get a retro/pixelated look.
resolution = pygame.display.Info()
width = resolution.current_w
height = resolution.current_h
dx = width // 900
dy = height // 500
This dx and dy can then be used to scale everything to a bigger size.
I would try this code:
import pygame
from pygame.locals import *
pygame.init() # You forgot the initialize the pygame window!
resolution = pygame.display.Info() # Get the users resolution
width = resolution.current_w
height = resolution.current_h
screen = pygame.display.set_mode((width, height), FULLSCREEN, 0, 32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill((255, 255, 255))
mouse_pos = pygame.mouse.get_pos()
pygame.draw.circle(screen, (0, 0, 255), mouse_pos, 20)
pygame.draw.circle(screen, (0, 0, 200), mouse_pos, 18)
pygame.draw.circle(screen, (0, 0, 100), mouse_pos, 15)
pygame.draw.circle(screen, (0, 0, 50), mouse_pos, 10)
pygame.display.flip()