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
Related
This question already has answers here:
How to scroll the background surface in PyGame?
(1 answer)
Making the background move sideways in pygame
(2 answers)
Closed 3 months ago.
i'm learning how to make a moving backround in pygame.
i learnd how to do it horizontal and trying now to do it vertical.
My problem is that my loop is not fully working , i manged to make it so the backround moves downward, but it wont make a third / fourth etc screen it just stops after 2 screens.
Thank you in advance for the help/ explenation. ^-^
import sys
import pygame
pygame.init()
fps = 60
framepersec = pygame.time.Clock()
white = (255, 255, 255)
screen_width = 400
screen_height = 600
display = pygame.display.set_mode((screen_width, screen_height))
display.fill(white)
pygame.display.set_caption("Backround test")
class Backround():
def __init__(self):
self.bgimage = pygame.image.load("image/test.png").convert()
self.rectbgimg = self.bgimage.get_rect()
self.bgy1 = 0
self.bgx1 = 0
self.bgy2 = -self.rectbgimg.height
self.bgx2 = 0
self.moving_speed = 3
def update(self):
self.bgy1 += self.moving_speed
self.bgy2 += self.moving_speed
if -self.rectbgimg.height >= self.bgy1:
self.bgy1 = self.rectbgimg.height
if -self.rectbgimg.height >= self.bgy2:
self.bgy2 = self.rectbgimg.height
def render(self):
display.blit(self.bgimage, (self.bgx1, self.bgy1))
display.blit(self.bgimage, (self.bgx2, self.bgy2))
backround = Backround()
while True:
framepersec.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
backround.update()
backround.render()
pygame.display.update()
This question already has answers here:
Why doesn't PyGame draw in the window before the delay or sleep?
(1 answer)
How to wait some time in pygame?
(3 answers)
Closed 2 years ago.
I am trying to make a program that displays a still image(IM1) on a screen all the time, then when a gpio port(Relay 1) is brought to ground have a new image(IM2) pop up and alternate between IM2 and its counterpart(IM3). Here is my code as of now:
import RPi.GPIO as GPIO
import pygame
from pygame.locals import *
clock = pygame.time.Clock()
pygame.init()
clock.tick(60)
screen = pygame.display.set_mode((1080, 1920))
IM1 = pygame.image.load("/home/pi/Desktop/Slides/Logo.jpg")
IM2 = pygame.image.load("/home/pi/Desktop/Slides/Works-1.jpg")
IM3 = pygame.image.load("/home/pi/Desktop/Slides/Works-2.jpg")
GPIO.setmode(GPIO.BOARD)
Relay1 = 11
GPIO.setup(Relay1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while(1):
if(GPIO.input(Relay1) == 0):
screen.blit(IM2, (0,0))
sleep(.5)
screen.blit(IM3, (0,0))
sleep(.5)
pygame.display.update()
else:
screen.blit(IM1, (0,0))
pygame.display.update()
#I can get IM1 to function but when Relay 1 is triggered only IM3 is displayed. I have tried using sprite and cant get that to work i was hoping to get this method to work.
You need to update the display after each blit. Do this:
screen.blit(IM2, (0,0))
pygame.display.update()
sleep(.5)
screen.blit(IM3, (0,0)
pygame.display.update()
sleep(.5)
The display is updated only if either pygame.display.update() or pygame.display.flip()
is called. See pygame.display.flip():
This will update the contents of the entire display.
Further you've to handles the events with pygame.event.pump(), before the update of the display becomes visible in the window.
See pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
If you want to display an image and delay the game, then you've to update the display and handle the events.
screen.blit(IM2, (0,0))
pygame.display.flip()
pygame.event.pump()
pygame.time.delay(delay * 500) # 0.5 second == 500 milliseconds
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.
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.
#Importing the pygame functions
import pygame
import sys
import os
from pygame.locals import *
#Allows for the editing of a window
pygame.init()
#Sets screen size
window = pygame.display.set_mode((800,600),0,32)
#Names the window
pygame.display.set_caption("TEST")
#Types of colors (red,green,blue)
black = (0,0,0)
blue = (0,0,255)
green = (0,255,0)
yellow = (255,255,0)
red = (255,0,0)
purple = (255,0,255)
lightblue = (0,255,255)
white = (255,255,255)
pink = (255,125,125)
clock = pygame.time.Clock()
L1="bolt_strike_0001.PNG"
L1=pygame.image.load(L1).convert_alpha()
L2="bolt_strike_0002.PNG"
L2=pygame.image.load(L2).convert_alpha()
L3="bolt_strike_0003.PNG"
L3=pygame.image.load(L3).convert_alpha()
L4="bolt_strike_0004.PNG"
L4=pygame.image.load(L4).convert_alpha()
lightingCurrentImage = 1
#Loop
gameLoop = True
while gameLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameLoop=False #Allows the user to exit the loop/game
window.fill(black) #used to fill the creen with the certian color variables
if (lightingCurrentImage==1):
window.blit(L1, (0,0))
if (lightingCurrentImage==2):
window.blit(L2, (0,0))
if (lightingCurrentImage==3):
window.blit(L3, (0,0))
if (lightingCurrentImage==4):
window.blit(L4, (0,0))
if (lightingCurrentImage==2):
lightingCurrentImage=1
if (lightingCurrentImage==3):
lightingCurrentImage=2
if (lightingCurrentImage==4):
lightingCurrentImage=3
else:
lightingCurrentImage+=3;
pygame.display.flip() #must flip the image o the color is visable
clock.tick(5)
pygame.quit() #quit the pygame interface
exit(0)
I'm having problems stitching together 10 images of a lightning bolt animation in pygame. What I have at the moment works but its not what I want it to look like. What happens when I run this is the lightning bolt creates the animation sequence once then disappears and never restarts the sequence again. If I set lightingCurrentImage+=3 to lightingCurrentImage+=2 it appears and stays on the screen but doesn't ever disappear. Please help me to see what the problem is if you can. Thanks! (I want the lightning bolt to begin and go all the way through the animation then disappear. Then begin again and repeat).
First create list of images then you can use it this way:
bold_imgs = []
bold_imgs.append( pygame.image.load("bolt_strike_0001.PNG").convert_alpha() )
bold_imgs.append( pygame.image.load("bolt_strike_0002.PNG").convert_alpha() )
bold_imgs.append( pygame.image.load("bolt_strike_0003.PNG").convert_alpha() )
bold_imgs.append( pygame.image.load("bolt_strike_0004.PNG").convert_alpha() )
lightingCurrentImage = 0
while True:
# here ... your code with events
window.fill(black)
window.blit( bold_imgs[ lightingCurrentImage ], (0,0))
lightingCurrentImage += 1
if lightingCurrentImage = len( bold_imgs ):
lightingCurrentImage = 0
pygame.display.flip()
clock.tick(5)
You can use tick(25) to get faster but smoother animation.
Human eye needs at least 25 images per second to see it as smooth animation.