python pygame screen displays black - python

I am new to python and made an algorithm I would like to visualize on a screen with pygame. This is my code:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Test screen")
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
But this always displays a black or kinda dark gray screen. Does anyone know what I'm doing wrong? I have tried multiple tutorials and they all give me the same screen.
I am using MacOS 10.14

You need to call the fill function on the win object. The background is always going to be black by default. The below example shows how to turn it to white.
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Test screen")
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(100)
## enter color here
win.fill((255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()

Related

How to get the X size of the screen in pygame? [duplicate]

I have created a window using
pygame.display.set_mode((width, height),
pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE)
Later on in the app I want to be able to ask that window its width and height so I can decide how to process the mouse position.
How do I access the dimensions of that pygame window elsewhere in the program? (event processing loop)
You want to get the surface, then get the size from the surface object.
Using tuple unpacking:
w, h = pygame.display.get_surface().get_size()
You can get the windows size by first getting the display surface. pygame.display.get_surface(), then calling get_width() / get_height() on the surface.
Like this!
surface = pygame.display.get_surface() #get the surface of the current active display
x,y = size = surface.get_width(), surface.get_height()#create an array of surface.width and surface.height
import pygame as pg
def create_window(width, height):
"""create a width x height resizable window/frame"""
win = pg.display.set_mode((width, height), pg.RESIZABLE)
# optional fill bg red, default is black
win.fill((255, 0, 0))
# optional title info
sf = "size x=%s y=%s" % (width, height)
pg.display.set_caption(sf)
# any extra code here ...
# draw a white circle
white = (255, 255, 255)
# center can be fixed or calculated for resize
center = (150, 150)
radius = 100
pg.draw.circle(win, white, center, radius)
pg.display.flip()
return win
pg.init()
width = 300
height = 200
win = create_window(width, height)
# event loop and exit conditions (windows titlebar x click)
while True:
for event in pg.event.get():
if event.type == pg.VIDEORESIZE:
width, height = event.size
# redraw win in new size
win = create_window(width, height)
print(win.get_size()) # test
if event.type == pg.QUIT:
raise SystemExit
Try this out.
Hope it helps.
Adding another answer since I haven't seen this one yet.
screen = pygame.display.set_mode() # Default to screen resolution.
area = screen.get_rect()
We can call get_rect() on screen because it is a surface object. area will be a Rect object, with (0, 0, width, height) information in it.
changed = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
if event.type == pygame.VIDEORESIZE:
scrsize = event.size # or event.w, event.h
screen = pygame.display.set_mode(scrsize,RESIZABLE)
changed = True
it's almost exactly like this in the comments for pygame.display.init doc page https://www.pygame.org/docs/ref/display.html#comment_pygame_display_update
edited only slightly from 2011-01-25T23:10:35 - Dave Burton thanks dave
gameDisplay = pygame.display.set_mode((800,600))
x=gameDisplay.get_width()
y=gameDisplay.get_height()
You can get the pygame.Surface object associated with the display with pygame.display.get_surface():
window_surface = pygame.display.get_surface()
Each Surface object can be asked for its with and height with get_width() respectively get_height():
window_width = pygame.display.get_surface().get_width()
window_height = pygame.display.get_surface().get_height()
get_size() returns a tuple with the width and height of the window:
window_width, window_height = pygame.display.get_surface().get_size()
get_rect() returns a rectangle the size of the window, always starting at (0, 0):
This can be used to get the center of the display:
window_center = pygame.display.get_surface().get_rect().center
It can even be used to limit the movement of an object to the window area:
object_rect = pygame.Rect(x, y, w, h)
object_rect.clamp_ip(pygame.display.get_surface().get_rect())
Minimal example:
import pygame
pygame.init()
pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
object_rect = pygame.Rect(pygame.display.get_surface().get_rect().center, (0, 0)).inflate(30, 30)
vel = 5
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))
keys = pygame.key.get_pressed()
object_rect.move_ip(
(keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel,
(keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel)
object_rect.clamp_ip(pygame.display.get_surface().get_rect())
pygame.display.get_surface().fill([64] * 3)
pygame.draw.rect(pygame.display.get_surface(), (255, 0, 0), object_rect)
pygame.display.flip()
pygame.quit()
exit()

Pygame: Efficient way to call draw function in for loops [duplicate]

I was coded a simple pygame grid window. but pygame window start lag after that.
Here is that simple code👇
import pygame
import random
pygame.init()
pygame.font.init()
screen_width = 500
screen_height = screen_width
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")
def drawGrid():
grid_list = []
blockSize = 25
for x in range(screen_width):
for y in range(screen_height):
rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
pygame.draw.rect(screen, (255,255,255), rect, 1)
running = True
while running:
screen.fill((0,0,0))
drawGrid()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
I was tried changing the call snippet of drawGrid() function position.
To improve the performance, do not construct the grind in every frame.
Create a pygame.Surface with the size of the window and draw the grid on this surface:
grid_surf = pygame.Surface((screen_width,screen_height))
drawGrid(grid_surf)
This surface is the back ground for your scene. blit it at the begin of every frame:
screen.blit(grid_surf, (0, 0))
Example code:
import pygame
import random
pygame.init()
pygame.font.init()
screen_width = 500
screen_height = screen_width
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")
def drawGrid(surf):
grid_list = []
blockSize = 25
for x in range(screen_width):
for y in range(screen_height):
rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
pygame.draw.rect(surf, (255,255,255), rect, 1)
grid_surf = pygame.Surface((screen_width,screen_height))
drawGrid(grid_surf)
running = True
while running:
screen.blit(grid_surf, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()

I'n creating my first game in pygame and i need help on showing up a screen when i press any key [duplicate]

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()

cs50 minesweeper algorithm sometimes stuck in forever loop [duplicate]

I was coded a simple pygame grid window. but pygame window start lag after that.
Here is that simple code👇
import pygame
import random
pygame.init()
pygame.font.init()
screen_width = 500
screen_height = screen_width
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")
def drawGrid():
grid_list = []
blockSize = 25
for x in range(screen_width):
for y in range(screen_height):
rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
pygame.draw.rect(screen, (255,255,255), rect, 1)
running = True
while running:
screen.fill((0,0,0))
drawGrid()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
I was tried changing the call snippet of drawGrid() function position.
To improve the performance, do not construct the grind in every frame.
Create a pygame.Surface with the size of the window and draw the grid on this surface:
grid_surf = pygame.Surface((screen_width,screen_height))
drawGrid(grid_surf)
This surface is the back ground for your scene. blit it at the begin of every frame:
screen.blit(grid_surf, (0, 0))
Example code:
import pygame
import random
pygame.init()
pygame.font.init()
screen_width = 500
screen_height = screen_width
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")
def drawGrid(surf):
grid_list = []
blockSize = 25
for x in range(screen_width):
for y in range(screen_height):
rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
pygame.draw.rect(surf, (255,255,255), rect, 1)
grid_surf = pygame.Surface((screen_width,screen_height))
drawGrid(grid_surf)
running = True
while running:
screen.blit(grid_surf, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()

Pygame: Rescale pixel size

With pygame, I created a 20x20 pixel window and added a 2x2 pixel rectangle.
When I run the program, the window size is super small and I can barely see the rectangle. How can I increase the window size whilst keeping the number of pixels constant, i.e. increase the pixel size? I am aware of this similar question, but there a somewhat more complicated case is discussed.
import pygame
screen_width, screen_height = 20, 20
x, y = 10, 10
rect_width, rect_height = 2, 2
vel = 2
black = (0, 0, 0)
white = (255, 255, 255)
pygame.init()
win = pygame.display.set_mode((screen_width, screen_height))
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill(black)
pygame.draw.rect(win, white, (x, y, rect_width, rect_height))
pygame.display.update()
pygame.quit()
Don't draw directly to the screen, but to another Surface.
Then scale that new Surface to the size of the screen and blit it onto the real screen surface.
Here's an example:
import pygame
screen_width, screen_height = 20, 20
scaling_factor = 6
x, y = 10, 10
rect_width, rect_height = 2, 2
vel = 2
black = (0, 0, 0)
white = (255, 255, 255)
pygame.init()
win = pygame.display.set_mode((screen_width*scaling_factor, screen_height*scaling_factor))
screen = pygame.Surface((screen_width, screen_height))
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill(black)
pygame.draw.rect(screen, white, (x, y, rect_width, rect_height))
win.blit(pygame.transform.scale(screen, win.get_rect().size), (0, 0))
pygame.display.update()
pygame.quit()

Categories