Using a background image in pygame window - python

I've got a simple python file which opens up a pygame window. When I click and release within the window, the program will tell me where my cursor was when I started clicking and where I released it. How do I include code to have a background image in the pygame window? So far, I only how to do this programs as stand-alone.
import pygame, sys
LEFT = 1
running = True
screen = pygame.display.set_mode((1200, 1000))
while running:
screen.fill((0,0,0))
pygame.display.flip()
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
print ("You pressed the left mouse button at (%d, %d)" % event.pos)
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
print ("You released the left mouse button at (%d, %d)" % event.pos)

You could use the following line to load an image:
my_image = pygame.image.load('my_image.png')
and then display it on the screen using the following line:
screen.blit(my_image, (x, y)) # screen = pygame.display.set_mode((1200, 1000))
also note that x and y indicate the position of the top left of the photo.

Related

How to fix pygame menu (space invaders)?

This is my first game so excuse the messy code. I am making a space invaders game and everything i implemented is working fine (sprites, function of the game, music, pause screen, etc). I wanted to implement a really simple menu screen where, if you press C, the game starts. However, the problem with this is that no matter where i call the menu function, there is always a problem, here is the code (im just going to post the menu function and main loop since everything else i believe is not needed).
import pygame
import random
import math
from pygame import mixer
# Start pygame
pygame.init()
# Create Screen
screen = pygame.display.set_mode((1000, 710))
# Background Image
background = pygame.image.load('background.png').convert_alpha()
# Menu Variables
menu_font = pygame.font.Font('freesansbold.ttf', 65)
menuX = 380
menuY = 250
# Menu Function
def game_intro(x, y):
menu = True
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
menu = False
if event.key == pygame.K_q:
pygame.quit()
quit()
# Menu Text
menu_text = menu_font.render("Space Invaders", True, (255, 255, 255))
screen.blit(menu_text, (x, y))
pygame.display.update()
# Game Loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
----game_intro(menuX,menuY)---IF I PUT IT HERE, THE ACTUAL GAME APPEARS FOR ONE SECOND AND IT GOES BACK TO MAIN MENU-----------
# Making the screen stay still
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
--------game_intro(menuX,menuY)--- IF I PUT IT HERE, THE GAME APPEARS ONLY WHEN 'c' IS BEING HELD DOWN-----------------
*more code*
# Updating
pygame.display.update()
if i put it above pygame.display.update(), then the same thing happens: the game appears for one second and then it goes back to the menu screen. I have tried to search everywhere but the videos either are from 2014, and the websites with some similar problem don't explain how to fix it. Please help.
First of all you should throw the while loop out of your function.
def game_intro(x, y):
# Menu Text
menu_text = menu_font.render("Space Invaders", True, (255, 255, 255))
screen.blit(menu_text, (x, y))
the missing code gets put in the mainloop like this
...
# Making the screen stay still
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
menu = False
if event.key == pygame.K_q:
pygame.quit()
...
now in your mainloop you need to decide whether to draw the menu or the game
if menu:
game_intro(x, y)
else:
#CODE THAT DRAWS THE GAME
all together:
import pygame
import random
import math
from pygame import mixer
# Start pygame
pygame.init()
# Create Screen
screen = pygame.display.set_mode((1000, 710))
# Background Image
background = pygame.image.load('background.png').convert_alpha()
# Menu Variables
menu_font = pygame.font.Font('freesansbold.ttf', 65)
menuX = 380
menuY = 250
# Menu Function
def game_intro(x, y):
# Menu Text
menu_text = menu_font.render("Space Invaders", True, (255, 255, 255))
screen.blit(menu_text, (x, y))
# Game Loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
# Making the screen stay still
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
menu = False
if event.key == pygame.K_q:
pygame.quit()
if menu:
game_intro(x, y)
else:
# CODE THAT DRAWS THE GAME
# Updating
pygame.display.update()
this should work
note that you need to set menu to True somewhere to get into the menu

Lock mouse in window Pygame

I want to make a FPS game in Pygame in windowed mode.
I need to be able to move my camera around for 360 degrees and more without limitation and with the hidden cursor.
I used Pygame's set_visible and set_pos but it doesn't prevent my mouse going out of the window and blocking on the screen borders.
import pygame
pygame.init()
game_display = pygame.display.set_mode((800,600))
pygame.mouse.set_visible(False)
exit = False
while (not exit):
pygame.mouse.set_pos = (400, 300)
mouse_move = (0,0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.MOUSEMOTION:
mouse_move = event.rel
if mouse_move != (0,0):
print(mouse_move)
pygame.quit()
You have to call pygame.event.set_grab(True) as well.
Better allow the users to exit with the Esc or another key, because they won't be able to click the x button anymore to close the window.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit = True

Why does the image not show up on the screen when I blit it?

Using Python (and Pygame), I have been creating a short one-screen game and I code each part in a different window. In my Home Screen, when I blit the play button onto the screen, it doesn't appear. I am new to Python and Pygame. This is my code:
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1352,638))
pygame.display.set_caption("Termination: Part 1")
bg = True
playButton = pygame.image.load("Play Button.png")
mouse = pygame.mouse.get_pos()
def playButtonFunction():
if background == pygame.image.load("Home Screen.png"):
background.blit(playButton(533.5,278))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN and event.key == K_SPACE:
bg = False
screen.blit(background,(0,0))
if bg:
background = pygame.image.load("Intro Screen.png")
else:
background = pygame.image.load("Home Screen.png")
playButtonFunction()
pygame.display.update()
As Frédéric Hamidi already said in a comment, the line
if background == pygame.image.load("Home Screen.png")
will not work as you probably expect.
You should probabkly pass a flag to that method or don't call that function at all when you don't want to show that playButton image.
Also, the line
background.blit(playButton(533.5,278))
will throw an exception, it should look like
background.blit(playButton, (533, 278))
So, change your code to
...
if bg:
background = pygame.image.load("Intro Screen.png")
else:
background = pygame.image.load("Home Screen.png")
screen.blit(background,(0,0))
if !bg:
background.blit(playButton, (533, 278))
...
Another issue that you load the images from disk every iteration of your game loop (with pygame.image.load). It's enough to load each image once.

Python/Pygame mouse position does not update (blit function)

I'm trying to make a simple menu using Pygame but I found that whenever I use pygame.mouse.get_position, it does blit what i want but i have to keep move my mouse to make my picture keep blitting.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('cursor test')
cursorPng = pygame.image.load('resources/images/cursor.png')
start = pygame.image.load('resources/images/menuStart.jpg')
enemy = pygame.image.load('resources/images/enemy-1.png')
white = (255,255,255)
black = (0,0,0)
clock = pygame.time.Clock()
FPS = 60
while True:
screen.fill(white)
pygame.mouse.set_visible(False)
x,y = pygame.mouse.get_pos()
x = x - cursorPng.get_width()/2
y = y - cursorPng.get_height()/2
screen.blit(cursorPng,(x,y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEMOTION:
if x < 50 and y < 250:
screen.blit(enemy,(100,100))
clock.tick(FPS)
pygame.display.update()
what's wrong?
Take a look at your code:
for event in pygame.event.get():
...
elif event.type == pygame.MOUSEMOTION:
if x < 50 and y < 250:
screen.blit(enemy,(100,100))
You check for events, and if you detect that the mouse is being moved (and only then), you draw the image to the screen.
If you want to draw the image even if the mouse is not being moved, just stop checking for the MOUSEMOTION event and simply draw the image always:
while True:
screen.fill(white)
pygame.mouse.set_visible(False)
x,y = pygame.mouse.get_pos()
x = x - cursorPng.get_width()/2
y = y - cursorPng.get_height()/2
screen.blit(cursorPng,(x,y))
if x < 50 and y < 250:
screen.blit(enemy,(100,100))
for event in pygame.event.get():
...
You need to blit into the screen a Surface and a Rect.
First, use this snippet I use for loading images. It makes sure the image is loaded correctly:
def loadImage(name, alpha=False):
"Loads given image"
try:
surface = pygame.image.load(name)
except pygame.error:
raise SystemExit('Could not load image "%s" %s' %
(name, pygame.get_error()))
if alpha:
corner = surface.get_at((0, 0))
surface.set_colorkey(corner, pygame.RLEACCEL)
return surface.convert_alpha()
Second, when you get the Surface, get its rect like this:
cursorSurf = loadImage('resources/images/cursor.png')
cursorRect = cursorSurf.get_rect()
Then, inside the update do the following:
cursorRect.center = pygame.mouse.get_pos()
And finnally, blit to screen like this:
screen.blit(cursorSurf, cursorRect)
Now you will notice your Mouse is being rendered correctly without having to move your mouse.

multiple clicks registering in pygame

I'm trying to make a board that changes color upon a left mouse click. But when I click it cycles through is_square_clicked() 3 times. That's a problem, I only want it to do it once. As you can probably guess this causes an issue for my program. So how do I limit it to 1 pass through per click? Thanks!
def is_square_clicked(mousepos):
x, y = mousepos
for i in xrange(ROWS):
for j in xrange(COLS):
for k in xrange(3):
if x >= grid[i][j][1] and x <= grid[i][j][1] + BLOCK:
if y >= grid[i][j][2] and y <= grid[i][j][2] + BLOCK:
if grid[i][j][0] == 0:
grid[i][j][0] = 1
elif grid[i][j][0] == 1:
grid[i][j][0] = 0
while __name__ == '__main__':
tickFPS = Clock.tick(fps)
pygame.display.set_caption("Press Esc to quit. FPS: %.2f" % (Clock.get_fps()))
draw_grid()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mousepos = pygame.mouse.get_pos()
is_square_clicked(mousepos)
pygame.display.update()
The reason that it cycles through is because you hold down the mouse long enough for it to check three times. I think if you have it wait between clicks, or you have it check not every time a cycle, it should be fixed.
im going to guess that since the game loops more than once each click it changes more then once
even though a click is very fast the loop is looping faster (depending on the FPS)
here is an example that will change the color of the screen on each click:
"""Very basic. Change the screen color with a mouse click."""
import os,sys #used for sys.exit and os.environ
import pygame #import the pygame module
from random import randint
class Control:
def __init__(self):
self.color = 0
def update(self,Surf):
self.event_loop() #Run the event loop every frame
Surf.fill(self.color) #Make updates to screen every frame
def event_loop(self):
for event in pygame.event.get(): #Check the events on the event queue
if event.type == pygame.MOUSEBUTTONDOWN:
#If the user clicks the screen, change the color.
self.color = [randint(0,255) for i in range(3)]
elif event.type == pygame.QUIT:
pygame.quit();sys.exit()
if __name__ == "__main__":
os.environ['SDL_VIDEO_CENTERED'] = '1' #Center the screen.
pygame.init() #Initialize Pygame
Screen = pygame.display.set_mode((500,500)) #Set the mode of the screen
MyClock = pygame.time.Clock() #Create a clock to restrict framerate
RunIt = Control()
while 1:
RunIt.update(Screen)
pygame.display.update() #Update the screen
MyClock.tick(60) #Restrict framerate
this code will blit a random color background each time you click so you can probably figure out the proper way to do it from the above code
Good Luck!

Categories