I have tried putting the fill color before blit but it won't work.
im using python 3.8.2, windows 10, and pygame 1.9.6.
please help
btw im following this tutorial (im new to pygame)
and here's my code
import pygame
#initialize
pygame.init()
#screen
screen = pygame.display.set_mode((800, 600))
#things
pygame.display.set_caption("space invaders 1.0")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
#player settings
playerimg = pygame.image.load('space-invaders.png')
playerx = 370
playery = 430
#define player
def player():
screen.blit(playerimg, (playerx, playery))
#loop
running = True
while running:
#rgb
screen.fill((10, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT():
running = False
player()
pygame.display.update()
#end process
pygame.quit()
exit()
ill answer any questions
(side note it crashes when I press "x" and exits when I press '-' idk why)
pygame.QUIT is not a function - it's a constant, simply an integer representing a QUIT event. You can't do if event.type == pygame.QUIT(), you need to do if event.type == pygame.QUIT, without parenthesis.
You also don't really need to call pygame.quit() and exit() at the end of the program - both pygame and the program itself will be terminated when the program reaches its end.
Apart from that your program works for me, images are showing. Make sure your image is visible over a black background and if it is and you are still having problems I'll try to help you with them.
I am trying to allow resizing for this app, I put the RESIZABLE flag, but when I try to resize, it messes up! Try my code.
It is a grid program, when the window resizes I want the grid to also resize/shrink.
import pygame,math
from pygame.locals import *
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
# This sets the width and height of each grid location
width=50
height=20
size=[500,500]
# This sets the margin between each cell
margin=1
# Initialize pygame
pygame.init()
# Set the height and width of the screen
screen=pygame.display.set_mode(size,RESIZABLE)
# Set title of screen
pygame.display.set_caption("My Game")
#Loop until the user clicks the close button.
done=False
# Used to manage how fast the screen updates
clock=pygame.time.Clock()
# -------- Main Program Loop -----------
while done==False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
if event.type == pygame.MOUSEBUTTONDOWN:
height+=10
# Set the screen background
screen.fill(black)
# Draw the grid
for row in range(int(math.ceil(size[1]/height))+1):
for column in range(int(math.ceil(size[0]/width))+1):
color = white
pygame.draw.rect(screen,color,[(margin+width)*column+margin,(margin+height)*row+margin,width,height])
# Limit to 20 frames per second
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit ()
Please tell me whats wrong, thanks.
The answer for this problem (allow the Pygame window and the surface inside it to resize) is simply to recreate the resizable window with an updated size, when the user changes its dimensions (done on pygame.VIDEORESIZE events).
>>> import pygame
>>> help(pygame.display.set_mode)
Help on built-in function set_mode in module pygame.display:
set_mode(...)
set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface
Initialize a window or screen for display
>>>
This removes all previous content on the window surface, so below
there's a process to continue with the current window content.
Some example code:
import pygame, sys
pygame.init()
# Create the window, saving it to a variable.
surface = pygame.display.set_mode((350, 250), pygame.RESIZABLE)
pygame.display.set_caption("Example resizable window")
while True:
surface.fill((255,255,255))
# Draw a red rectangle that resizes with the window.
pygame.draw.rect(surface, (200,0,0), (surface.get_width()/3,
surface.get_height()/3, surface.get_width()/3,
surface.get_height()/3))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == pygame.VIDEORESIZE:
# There's some code to add back window content here.
surface = pygame.display.set_mode((event.w, event.h),
pygame.RESIZABLE)
How to continue with the current window content:
Here's some steps to add back the previous window content:
make a second variable, set to the value of the old window surface variable.
create the new window, storing it as the old variable.
draw the second surface onto the first one (old variable) - use the blit function.
use this variable and delete the new variable (optional, use del) to not use extra memory.
Some example code for the above steps (replaces pygame.VIDEORESIZE event if statement):
if event.type == pygame.VIDEORESIZE:
old_surface_saved = surface
surface = pygame.display.set_mode((event.w, event.h),
pygame.RESIZABLE)
# On the next line, if only part of the window
# needs to be copied, there's some other options.
surface.blit(old_surface_saved, (0,0))
del old_surface_saved
You are not updating your width, height, or size when the window changes.
From the docs: http://www.pygame.org/docs/ref/display.html
If the display is set with the pygame.RESIZABLE flag,
pygame.VIDEORESIZE events will be sent when the user adjusts the
window dimensions.
You can get the new size, w, h from the event VIDEORESIZE http://www.pygame.org/docs/ref/event.html
A simple Hello World window that is resizable, plus I was playing around with classes.
Broken down into two files, one for defining the colour constants.
import pygame, sys
from pygame.locals import *
from colors import *
# Data Definition
class helloWorld:
'''Create a resizable hello world window'''
def __init__(self):
pygame.init()
self.width = 300
self.height = 300
DISPLAYSURF = pygame.display.set_mode((self.width,self.height), RESIZABLE)
DISPLAYSURF.fill(WHITE)
def run(self):
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == VIDEORESIZE:
self.CreateWindow(event.w,event.h)
pygame.display.update()
def CreateWindow(self,width,height):
'''Updates the window width and height '''
pygame.display.set_caption("Press ESC to quit")
DISPLAYSURF = pygame.display.set_mode((width,height),RESIZABLE)
DISPLAYSURF.fill(WHITE)
if __name__ == '__main__':
helloWorld().run()
colors.py:
BLACK = (0, 0,0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
BLUE = (0,0,255)
GREEN = (0,255,0)
A simple way to do which I found was the following code snippet
# Imports
from vars import *
from pygame.locals import *
# Main init
pygame.init()
# Basic vars
run = True
s_width = 1000
s_height = 600
# Making display screen. Don't forget the last tag!
screen = pygame.display.set_mode((s_width, s_height), RESIZABLE)
# Main loop
while run:
# event detection
for event in pygame.event.get():
if event.type == QUIT:
run = False
# The part which matters for our purposes
if event.type == WINDOWRESIZED:
s_width, s_height = screen.get_width(), screen.get_height()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
# Test line to see if the window resizing works properly
pygame.draw.line(screen, (255, 255, 255), (int(0.3*s_width), int(0.25*s_height)), (int(0.8*s_width), int(0.25*s_height)))
# Final flip
pygame.display.flip()
# Quit
pygame.quit()
What this does is allows the pygame window to be resized. But since you often have the placing and sizes of a lot of elements/sprites depending on the s_width and s_height, it also detects when the window size is changed and adjusts the dimensions accordingly.
First, You don't detect the new window size before redrawing the screen.
Add the get_size() method at line 45 and it works:
#--------------------------------------------------------------
# Draw the grid
size = pygame.display.get_surface().get_size() // size update
for row in range(int(math.ceil(size[1]/height))+1):
#---------------------------------------------------------
Then you work with a fixed cell size (50, 20) and fill as many cells as possible. If You want to GROW/SHRINK the cells when resizing the window, You will have to define the NUMBER of cells per line/row, then calculate the cell size, then draw them.
I've tried so many ways of changing a pixel in Pygame, and none of them works with me...
import pygame
import random
width = 640
height = 400
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
running = True
while running:
x = random.randint(0, width-1)
y = random.randint(0, height-1)
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
screen.set_at((x, y), (red, green, blue))
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
clock.tick(240)
Nothing happens, just the black screen until I close it.
It looks like you're following this tutorial but you've indented a few essential lines in the wrong place. Remember, Python is white space sensitive; indentation matters!
The last two lines should not be inside the for loop block, they should be in the while loop block.
while running:
# code that draws pixel
pygame.display.flip()
clock.tick(240)
These lines update the display and compute the time between frames.
The way you had it, inside the if statement, the pixel would never get drawn until the pygame.QUIT event was triggered.
I want to move the apple image to a random position whenever i click it.The first time i click it , it works well but next time i try to do it , it gives me no response.
Here is the code:
import pygame
pygame.init()
foodimg=pygame.image.load("food.png")
foodrect=foodimg.get_rect()
white = (255,255,255)
#Game Display
display_width = 1080
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Click It! ~ Snapnel Productions')
gameDisplay.fill((white))
running=True
while running:
gameDisplay.fill((white))
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
x, y = event.pos
if foodimg.get_rect().collidepoint(x, y):
foodrect.center=(random.randint(5,1060),random.randint(5,700))
print "Hi",
continue
gameDisplay.blit(foodimg,foodrect)
pygame.display.flip()
is the food image.
Change the line
if foodimg.get_rect().collidepoint(x, y):
to
if foodrect.collidepoint(x, y):
Your code didn't work because the rectangle of the picture never moves, it's always going to be <rect(0, 0, 30, 30)>. Foodrect actually represents where your rectangle is located and it's the rect whos values you change when you run foodrect.center =. You want to check if the mouse click is colliding with the real rect, not the rect of the image.
I've just started learning Pygame . I'm following this tutorial.
I ran the following program but it shows black color instead of blue :
import pygame
h = input("Enter the height of the window : ")
w = input("Enter the width of the window : ")
screen = pygame.display.set_mode((w,h))
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running=0
screen.fill((0,0,1))
pygame.display.flip()
For Blue color, you should use 255 as the third element in the tuple, not 1.
Example -
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running=0
screen.fill((0,0,255))
pygame.display.flip()
It shows black because you're running the screen.fill() after your game loop. This means it will only fill the screen after you're done playing.
Best practice is to put it somewhere inside the loop, and then any sprites you want to draw should be done after - so that if the sprite moves, its old position will be colored over by the background.
Also, as mentioned in other answers: (0,0,1) is black with the barest hint of blue. A good rgb colour-picker can be found by googling "rgb color picker".
Finally, you should change out "event=pygame.event.poll()" to be "for event in pygame.event.get()" as shown, as this will allow it to detect multiple events simultaneously. Unnecessary for this example, obviously, but I assume it wouldn't be left as a blue screen that can only be closed.
import pygame
pygame.init()
h = input("Enter the height of the window : ")
w = input("Enter the width of the window : ")
screen = pygame.display.set_mode((w,h))
running = True
while running:
for event in pygame.event.poll():
if event.type == pygame.QUIT:
running=0
#any additional event checks
screen.fill((0,0,255))
#any additional drawings
pygame.display.flip()
pygame.quit()