Pygame - adding background image - python

I am new to python and created a small game. I want to add a background image, but is is not working. The image is not displayed.
i tried it with the following code:
background = pygame.image.load("images\\background.png")
screen.blit(background,(0,0))

The code in the question does not really illustrate the problem. But if the code is generating the error:
background = pygame.image.load('images/background.png')
pygame.error: Couldn't open images/background.png
Then it is simply that PyGame can't find the specified image file.
However I expect that your code is simply not "flushing" the updates to the window / screen with a call to pygame.display.flip()
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
### MAIN
pygame.init()
SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), SURFACE )
pygame.display.set_caption("Background Image")
background_image = pygame.image.load('images/grass.png')
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# Movement keys
keys = pygame.key.get_pressed()
if ( keys[pygame.K_UP] ):
print("up")
#elif ...
# Update the window, but not more than 60fps
window.blit( background_image, ( 0,0 ) )
pygame.display.flip() # <-- Flush drawing ops to the screen
# Clamp FPS
clock.tick_busy_loop( 60 )
pygame.quit()
Note the 4th-last line.

Take a look at this page on StackOverflow. It has multiple solutions that you can use. I'll write one of them here.
You can make an image the size of your game window, then before anything else is displayed, blit it to (0,0).
bg = pygame.image.load("background.png")
#INSIDE OF THE GAME LOOP
gameDisplay.blit(bg, (0, 0))
#OTHER GAME ITEMS
I hope this helps you!

Related

Making a Semi-Transparent Pause Background screen in Pygame

I was wondering if anyone out there would be able to help me with my problem. Currently I want to display a pause screen everytime a certain key is pressed, which it does however the resulting screen is always either fully transparent or non-transparent and was wondering if there was any way that I would be able to adjust the following code in order to make that dream a reality.
Here's where the Pause Screen is called:
if event.key == pygame.K_p:
notPaused = False
#print("Obtained")
pause = Pause(self.pauseScreen)
while notPaused == False:
#print("Received")
notPaused = pause.processEvents()
print(str(notPaused))
pause.displayFrame(self.pauseScreen)
clock = pygame.time.Clock()
clock.tick(60)
And here's how the pause screen displays itself:
screen.fill(constants.BLACK)
font = pygame.font.SysFont("serif", 25)
for counter in range(1,5):
text = font.render(self.options[counter-1], True, constants.WHITE)
center_x = 150
center_y = (counter * 120) - (text.get_height() // 2) + (self.pointer.image.get_height() // 2)
screen.blit(text, [center_x, center_y])
self.active_sprite_list.draw(screen)
pygame.display.flip()
And for anyone wondering I sometimes try to sub out BLACK for ABLACK using the RGBA values of: (0,0,0,125)
Finally this is where the screen is initialized for the pause screen:
self.size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
self.pauseScreen = pygame.Surface(self.size,pygame.SRCALPHA,32)
Any and all help is appreciated.
You should build up your pause screen as a separate surface. This command: screen.fill(constants.BLACK) all but ensures you will never get 50% transparency (since everything that was on your screen before has been painted over with black).
Build a new surface for your pause screen, fill it black, add your text; then use something like my_pause_surface.set_alpha(128) to make that whole surface 50% transparent, then blit it on top of the rest of your game.
Here is some useful information in another question: Draw a transparent rectangle in pygame

box around cursor pygame

In the little games I made in pygame there's always a box around my cursor in which all colours are reversed (e.g. if I hold my cursor over a black and red background the square around the cursor will be white and cyan). This initially wasn't a problem, since the first few projects only required keyboard inputs, but now I want to make a game where you have to click a lot, so it would look very ugly. How do I remove this box? I am using macOS High Sierra, python3 and pygame 1.9.3.
I'm putting this as an answer, because it's too much for a comment. Also, I don't have a Mac, so this answer is supposition.
Looking at the github issue #Keno posted:
There's an image of a white cursor (black filled outline), on a black background.
It looks to me, that with the latest OS upgrade, MacOS is no longer working correctly with whatever mouse-cursor-image functions PyGame is using. Obviously the pixels outside the cursor should be transparent.
Anecdotal evidence (i.e.: a google search) suggests that other software has cursor issues with macOS High Sierra too.
Maybe it's possible to work around the problem.
If the PyGame application is not using the mouse, it may be useful to just hide the cursor.
pygame.mouse.set_visible() # Perhaps this just gives a black-box though
However if PyGame is "hiding" the mouse by setting a fully-transparent cursor, the result may still be a completely black square. So the mouse can be moved outside the window (or at least to the bottom-right corner):
w, h = pygame.display.get_surface().get_size() # get window size
pygame.mouse.set_pos( [w, h] ) # move cursor outside window
I got a bit carried away with this problem, and ended up writing a bunch of test cases.
import sys
import time
import pygame
from pygame.locals import *
WHITE = 255,255,255
BLUE = 0,0,60
WINDOW_WIDTH=600
WINDOW_HEIGHT=500
pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.font.init()
clock = pygame.time.Clock()
text_font = pygame.font.Font(None,60)
STARTUP_MS = int(time.time() * 1000.0) # Epoch time programme started
MANUAL_CURSOR = pygame.image.load('finger_cursor_16.png').convert_alpha()
cursor_test = 0
time_last_test = 0
while (True):
NOW_MS = int(time.time() * 1000.0) - STARTUP_MS # current time in milliseconds-since-start
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Try different cursor styles
if ( cursor_test == 4 ):
text_image = text_font.render( 'Off-Screen-Cursor', True, WHITE )
pygame.mouse.set_pos( [ WINDOW_WIDTH, WINDOW_HEIGHT ])
pygame.mouse.set_visible(True)
elif ( cursor_test == 3 ):
text_image = text_font.render( 'Manual-Cursor', True, WHITE )
pygame.mouse.set_visible(False)
# cursor drawn as part of the screen, see below
elif ( cursor_test == 2 ):
text_image = text_font.render( 'Transparent-Cursor', True, WHITE )
pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))
pygame.mouse.set_visible(True)
elif ( cursor_test == 1 ):
text_image = text_font.render( 'Hidden-Cursor', True, WHITE )
pygame.mouse.set_visible(False)
elif ( cursor_test == 0 ):
text_image = text_font.render( 'Default-Arrow-Cursor', True, WHITE )
pygame.mouse.set_visible(True)
pygame.mouse.set_cursor(*pygame.cursors.arrow)
# test for 3-seconds each
if ( NOW_MS - time_last_test > 3000 ):
pygame.mouse.set_pos( [ WINDOW_WIDTH//2, WINDOW_HEIGHT//2 ])
time_last_test = NOW_MS
cursor_test += 1
if ( cursor_test > 4 ):
cursor_test = 0
# Paint the screen
screen.fill(BLUE)
# Write the mode
screen.blit(text_image, ( 0, 0 ))
# if we're in manual-cursor mode, paint a cursor too
if (cursor_test == 3):
screen.blit( MANUAL_CURSOR, ( pygame.mouse.get_pos() ) )
pygame.display.update()
clock.tick_busy_loop(60)
EDIT: I forgot to upload the finger_cursor_16.png image:
Just adding to #Kingsley answer without the tests and out of window cursor detection, still super hacky and probably more trouble than it's worth but might help you while there's a fix.
import sys, pygame, os
from pygame.locals import *
def main():
pygame.init()
screen = pygame.display.set_mode((600,600))
screen.fill((100, 100, 100))
# http://tobiasahlin.com/blog/common-mac-os-x-lion-cursors/
custom_cursor = pygame.image.load(os.path.join('yourPath', 'pointer.png')).convert_alpha()
# MAIN LOOP:
while True:
# EVENTS :
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# Press Q to quit
elif event.type == KEYDOWN and event.key == K_q:
sys.exit()
pygame.mouse.set_visible(False)
screen.fill((100,100,100))
if pygame.mouse.get_focused():
screen.blit( custom_cursor, ( pygame.mouse.get_pos() ) )
pygame.display.flip()
if __name__ == '__main__': main()

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)

Pygame FULLSCREEN Display Flag Creates A Game Screen That Is Too Large For The Screen

UPDATED ISSUE
I have discovered the issue appears to be with the fact that I am using the FULLSCREEN display flag to create the window. I added a rectangle to be drawn in the top left of the scree (0, 0), but when I run the program, It is mostly off the screen. Then, when I Alt-Tab away and back, the rectangle is appropriately placed at 0,0 and the turret is off center.
So basically, when the program starts, the game screen is larger than my actual screen, but centered. Then after Alt-Tab, the game screen is lined up with 0,0 but since the game screen is larger than my screen, the turret looks off center, but is actually centered relative to the game.
So the real question is why does using the FULLSCREEN display flag make a screen larger than my computer screen?
ORIGINAL ISSUE
I am building a simple demonstration of a turret in the center of the screen which follows the location of the cursor as if to fire where it is. Everything works perfectly until I Alt-Tab away from the screen, and then Alt-Tab back. At this point to turret is now off center (down and to the right)
import pygame, math
pygame.init()
image_library = {}
screen_dimen = pygame.display.Info()
print("Screen Dimensions ", screen_dimen)
def get_image(name):
if name not in image_library:
image = pygame.image.load(name)
image_library[name] = image
else:
image = image_library[name]
return image
robot_turret_image = get_image('robot_turret.png')
screen = pygame.display.set_mode((0, 0), pygame.`FULLSCREEN`)
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEMOTION:
print(event.pos)
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
done = True
screen.fill((0, 0, 0))
pos = pygame.mouse.get_pos()
angle = 360 - math.atan2(pos[1] - (screen_dimen.current_h / 2),
pos[0] - (screen_dimen.current_w / 2)) * 180 / math.pi
rot_image = pygame.transform.rotate(robot_turret_image, angle)
rect = rot_image.get_rect(center=(screen_dimen.current_w / 2, screen_dimen.current_h / 2))
screen.blit(rot_image, rect)
color = (0, 128, 255)
pygame.draw.rect(screen, color, pygame.Rect(0, 0, 200, 200))
pygame.display.update()
clock.tick(60)
It seems that the center is now off. I have printed out the screen dimensions before and after the Alt-Tab and they are the same, so I can't figure out why the image moves. I believe I am missing something regarding state changes with Pygame, but can't figure out what. If it is relevant, I am on Windows 10.
Alright, I discovered a solution from gamedev.stackexchange
And I will re-hash it here. The issue was that Using the fullscreen tag was making a screen larger than my computer screen. The following code solves this
import ctypes
ctypes.windll.user32.SetProcessDPIAware()
true_res = (ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
pygame.display.set_mode(true_res,pygame.FULLSCREEN)
It is important to note that this is potentially just a windows fix, but I do not have another system with which to test it on. But It works on Windows 10 with python 3.5.1 and pygame 1.9.2a0

How do I add more than 2 sprites into an animation in pygame?

#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.

Categories